0

In the old days, we used to use jQuery's .live() (http://api.jquery.com/live/) to bind to future events, if content was reloaded via AJAX, for example.

Since .live() is now deprecated (and removed), jQuery suggest the use of .on() ( http://api.jquery.com/on/) instead. They do not state that it works for future events. Incidentally, it's not working on elements reloaded via AJAX.

My question; does .on() work, or is it supposed to work for future events, in the way that .live() does/used to?

I'm calling .on() as follows:

$j('#header-cart').on('click', '.skip-link-close', function(e) {
    ... // change the world
});

Thanks.

Jongosi
  • 2,305
  • 1
  • 28
  • 31

3 Answers3

2

You need to attach the event .on() in different way when replaced with .live()

For live

$('#ele_id').live('click', function() { 
  // event code
});

For on:

$(document).on('click', '#ele_id', function() { 
  //  event code
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

I feel that you are calling $.on in a wrong way! Yes, it is the replacement for .live(), which was awesome.

Have a static element: #static-div and the dynamic content, say .dynamic-link, inside that <div>. You need to call .on() this way:

$("#static-div").on("click", ".dynamic-link", function(e){
   e.preventDefault();
});

Or, if you are not at all sure, you can do this way:

$(document).on("click", ".dynamic-link", function(e){
   e.preventDefault();
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

Yes it does, it works in a very similar way to live with the difference that you do not bind the event to a future element but to an underlying static element. .on makes use of event propagation / bubbling.

As an example

<div class="static-element">
    <div>
        <!-- Content inserted from ajax call below -->
        <p class="volatile-element">Example content</p>
    </div>
</div>

With .on bind to the static element and target the volatile element.

$(".static-element").on("click", ".volatile-element", function(event) { ... });
David Barker
  • 14,484
  • 3
  • 48
  • 77