March 18, 2013

JQuery on click not working

Question by Jamie Fearon

I’m having strange behaviour where within the same file a change event is working but a click event isn’t. I understand I may have not posted enough code, but I just want to see if anyone knows why on event may work but another will not. Here is my code:

class AddBTS
  constructor: () ->

    $('#a').on 'change', (evt) => @a evt
    $('#b').on 'change', (evt) => @b evt
    $('#c').on 'click', (evt) => @c


  a: (evt) =>
    console.log 'a works'

  b: (evt) =>
    console.log 'b works'

  c: () =>
    console.log 'c works'

The html it refers to:

<input type="file" id="a">
<input type="file" id="b">
<button id="c">OK</button>

The events work fine on a and b, but the click event doesn’t work on c.

My compiled JS is executed after the DOM loads.

Could anyone give me some pointers on what may cause this and I will try it out.

Interestingly, when I double click on c I get the following error:

Error in event handler for 'undefined': IndexSizeError: DOM Exception 1 Error: Index or size was negative, or greater than the allowed value.

Answer by user1737909

You have to call your c function :

@c()

Without parens, you’re only accessing it. Remember, CoffeeScript isn’t Ruby ;).

Answer by Starx

I dont think you need the evt since you are not using it.

$('#c').on 'click', () => @c

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!