cgwebprojects
cgwebprojects

Reputation: 3472

Jquery changing .live to .on,

I am trying to change all my .live() to .on() as the prior is now deprecated.

I am struggling to understand how it works though. Before I used this code and it worked fine...

$('#lightBoxClose').live('click', function() {
    $('#lightBox').fadeOut();
});

So I tried changing it to,

$('#lightBoxClose').on('click', function() {
    $('#lightBox').fadeOut();
});

But it doesn't work can anyone please explain what I am supposed to be doing thanks.

Upvotes: 5

Views: 2333

Answers (2)

bfavaretto
bfavaretto

Reputation: 71908

You have to bind to an element that already exists at the time of the binding, passing the target selector as the second argument. That element must be an ancestor of the eventual click target, so it can catch the bubbled event. This technique is called delegation.

For example, using the document element:

$(document).on('click', '#lightBoxClose', function() {
    $('#lightBox').fadeOut();
});

Upvotes: 11

jeremyharris
jeremyharris

Reputation: 7882

Please use the search before posting, as it's posted all around SO.

See: JQuery switching application from "live" to "on" method

$(document).on('click', '#lightBoxClose', function() {
    $('#lightBox').fadeOut();
});

Upvotes: 2

Related Questions