J D
J D

Reputation: 1818

Keyup Blur functions

Why does

$(document).on("keyup blur", "#my_selector", function() {
    //DO SOMETHING
});

seems to work, however

$("#my_selector").on("keyup blur", function() {
    //DO SOMETHING
});

Doesn't? I put them both in my ready functions, and while the above one works, the lower one doesn't. This is in context of my previous question.

Upvotes: 3

Views: 806

Answers (2)

x10
x10

Reputation: 3834

$('selector').on('event') works like $.bind.
$(document).on('event', 'selector') works like $.live.

In other words, $('selector').on attaches an event handler to a currently existing node.

If $('#my_selector') is empty at the time of the event handler's creation, the event handler will not be attached to it.

On the other hand $(document) is always available, and you can always attach event handlers to it.
$(document).on('event', 'selector', function() { ... }) attaches an event handler to document and filters it by 'selector'. So this works just like $().live() in previous versions of jQuery, and you should use event binding in this way.

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

If the #my_selector item is added dynamically (e.g. after an Ajax call finishes) then you may be attaching the direct event handler before the element exists in the DOM. In this case the event handler would be attached to nothing. The first one attaches a delegated event handler so it does not matter when the element appears in the DOM, the event handler would be executed.

Upvotes: 3

Related Questions