1

I have below js which the event is not fire after ajax append the content

$(".item").mouseenter(function(){ $(this).children('.delete').show(); });

$(".item").mouseleave(function(){ $(this).children('.delete').hide(); });

$(".delete").click(function(){
    $(this).parent().hide(); });

$("#add").click(function(){
  action = 'addItem';
  $.ajax({
    type: "POST",
    url: "/echo/json/",
    data: 'action='+action,
    cache: false,
    success: function(json){
        $(".main").append('<div class="item"><div class="content"> content new </div><div class="delete"> delete </div></div>');
    }
  });
});

Please check out the jsfiddle at http://jsfiddle.net/3j5L2/19/

How do I ensure no matter how many item I added in, the mouseenter and mouseleave event get fired?

jned29
  • 477
  • 12
  • 50
Peter
  • 1,481
  • 4
  • 19
  • 37
  • 1
    Or one of [the others..](https://www.google.com/#q=jquery+event+dynamic+element+site:stackoverflow.com) – George Aug 04 '14 at 08:31

2 Answers2

0

You need to use event delegation with jQuery's on method:

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.

$('.main').on('mouseenter', '.item', function() {
    ...
});

Assuming your .main element isn't dynamically created, this event listener will be assigned to the .main element and will only trigger when the event occurs to that specific descendant.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

You need event delegation for binding events to dynamically added elements:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(".main").on('click','.delete',function(){
   $(this).parent().hide();
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125