what happens if the element I am binding jQuery code to is not found on the page?
Does the previous binded code breaks?
Let me explain it with a sample. I have the following code inside my page:
<script type="text/javascript">
$(document).ready(function() {
$('.deleteMemo').live('click', function() {
$.ajax({
[ajax call omitted for brevity]
});
});
$('.markAsViewed').live('click', function() {
$.ajax({
[ajax call omitted for brevity]
});
});
});
</script>
Now, depending on the page status in the page there could be:
- Only elements with “deleteMemo” class
- Only elements with “markAsViewed” class
- Both
I am experimentig that, in the first case (only “deleteMemo” elements), the jQuery code does’nt get called at all. I still have not did a try with the other cases but I have triple checked the code and even looked at it with fiddler.
Any suggestion?
It does not matter if the elements are on the page when calling
.live()because.live()does not bind the handler to the actual elements.This is the purpose of using
.live(). It allows elements that are dynamically added to the page to fire a handler that was added before they existed.If any ancestors of a
.deleteMemo(for example) stops event bubbling from taking place, thenlive()will not work for that element.So if you have any click handlers on any of the ancestors that either have:
or:
…in them, the
live()handler will not fire.Of course if the selector doesn’t match (check capitalization for example) then the handler won’t fire.