0

I recently got a problem that

$('.klass').change(function () { ... });

was not firing in some situations and found the solution on SO to use

$(document).on('change', '.klass', function () { ... });

instead. The explaination was that my element was created after declaration of the listener or something else was blocking it from firing.

So I should probably never use the first method? And use the second method for any event (click, change, ...):

$(document).on('event', 'jquery-selector', function () { ... });

Could someone please explain the difference between the two and possible gotchas.

xaxa
  • 1,057
  • 1
  • 24
  • 53
  • This might help you : http://stackoverflow.com/questions/8042576/whats-the-difference-between-jquery-live-and-on – Rohit Arora Jun 09 '15 at 17:39

3 Answers3

2

change calls .on

$().change = function( types, data, fn ) {
    return this.on( types, null, data, fn );
}
SeinopSys
  • 8,787
  • 10
  • 62
  • 110
2

The first method is fine, but as you said, you need to make sure that your element has been loaded into the DOM before you create your event handler.

$(document).ready(function () {
   // dom has been loaded, now you can attach event handlers
})

As @wZVanG sort of said, change() is just sugar for calling on, there is no practical difference.

azium
  • 20,056
  • 7
  • 57
  • 79
1

The main difference is that the second one allows the use of multiple events. Instead of saying

$('.klass').click(function(){
    //some content
});
$('.klass').change(function(){
    //same exact content, repeated
});

You can instead write

$('.klass').on('click change', function(){
    //some content, it applies to both now.
});

or you can use the (somewhat superfluous)

$(document).on('click change', '.klass', function(){
    //some content, it still applies to both.
});
RoboticRenaissance
  • 1,130
  • 1
  • 10
  • 17