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

61 Views Asked by At

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/read an element while maintaining the same delegated events bound to it?

FYI, I'm using jQuery 1.9.

1

There are 1 best solutions below

0
On

Don't bound listeners to the parent element you occasionally remove, but to the one that is always there, in your example it's the #element_list_parent

You could go with:

var events = "mouseenter mouseleave click";

$("#element_list_parent").on(events, "img.image_class, .empty_message", function(e){
  //do stuff for event
});

than if you need to recognize the event-to-element :

$("#element_list_parent").on(events, "img.image_class, .empty_message", function(e){

    if(e.target.className=='image_class'){
         // do something for images
    }else{
         // do else for .empty_message DIV
    }

});