I'm working on a project, in which when I keep pressing on the min/plus button without hovering off the picture with the .live()
method, the function works. In the case of .on()
method the function does not work.
How can I fix this issue, so it works for .on()
method as well?
Here is an example of what I’m referring too (I fixed the error in this example, but I was using the .on
method wrong).
You're not using it correctly. The replacement for .live()
is $(document).on()
with the event and handler being passed in, of course... for example:
$(document).on('click', '#myElement', function() {
//... some function ...
});
It's worth mentioning that before .on()
ever came around, .live()
was already considered an inefficient way to handle this kind of binding. .delegate()
was recommended instead, and now .on()
(using the delegator syntax).
Or as an example: instead of the document being the listener (which is what .live()
used to do), you should pick the nearest ancestor that does not get destroyed with DOM manipulations. I honestly find the "jsdo.it" a bit clunky to use so I don't have the specific element in mind, but for example, given the structure:
<div id="ajax_container">
<button id="do_something">Clicky!</button>
<p>Some dynamically-loaded content</p>
</div>
Where the contents of ajax_container
are replaced by an Ajax call (no need to show the code for that part), binding a non-destroyed listener (the container div) for that button's click event would look like:
$('#ajax_container').on('click', '#do_something', function() {
// do something
})
You'll have to post some code to be certain as to why your implementation was not working, but you should view the jQuery source for examples of how to use .on() and .live()
<div id="parent">
<a href="#" id="anchor">Click Me</a>
</div>
$('#anchor').live('click',function() { }):
$('#parent').on('click','#anchor',function() { });
$('#anchor').on('click',function() { });
The .live() event listener is added to the document element so that the callback will be fired as long as the event bubbles all the way up to the document element
In the second example ( $('#parent').on() ), the event listener is added to the parent element and is fired every time a click event bubbles up to #parent and comes from (or interacts with along the way) an element named #anchor
The third example ( $('#anchor').on() ) adds the event listener directly to the anchor element itself and is the exact same as $('#anchor').bind('click',function() { });
The reason why .live() was introduced was so that if your page structure changes, event callbacks can still be fired because the event listener itself is attached to the document element.
You can use on in a similar method, but it has to be attached itself to an element that is not removed from the page - if that element is removed, then so are all the event listeners along with it.
http://api.jquery.com/on/
http://api.jquery.com/live/