Monday, 9 September 2013

Maintaining delegated event binding after removal of bound element(s)

Maintaining delegated event binding after removal of bound element(s)

In a view, I have an unordered list to display elements that are bound to
a user dropdown selection. These list elements are appended dynamically
based on the server response.
The HTML looks like
<div id = "element_list_parent">
<ul id = "element_list">
</ul>
</div>
These elements all have mouseover, mouseout and click events bound to them
via
$("#element_list").on("$event", "img.image_class", function(e){
//do stuff for event
});
Sometimes, there is an empty query returned from the server. In that case,
I have
$("#element_list").remove();
$("#element_list_parent").html("<div class = 'empty_message'>No
Results</div>");
I found that if I selected an option where there were no items to be
appended to 'element_list', and then selected an option with numerous
appended items, the delegated events would not work.
Is it possible to remove/readd an element while maintaining the same
delegated events bound to it?
FYI, I'm using jQuery 1.9.

No comments:

Post a Comment