xaxa
xaxa

Reputation: 1159

Difference between document.on('event') and $().event

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.

Upvotes: 1

Views: 254

Answers (3)

RoboticRenaissance
RoboticRenaissance

Reputation: 1187

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.
});

Upvotes: 1

azium
azium

Reputation: 20614

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.

Upvotes: 2

change calls .on

$().change = function( types, data, fn ) {
    return this.on( types, null, data, fn );
}

Upvotes: 3

Related Questions