0

I have a file like this for my html:

<div id="append">
     <div class="sample"> Sample Text 1 </div>
</div>

In my jquery file, this is what i do to append the rest of the divisions,

$.each([ 2,3,4,5,6,7,8,9,10 ], function( index, value ) {
      $('#append').append("<div class="sample"> Sample Text "+ value.toString() + " </div>");
});

The problem that I am having is that the appended divisions (Sample Text 2 and more) cannot detect a mouse enter event. I tested it by doing this:

$("div.sample").mouseenter(function(){
    alert("Mouse Enter Event Detected");
});

I only get the alert when hovering over the first div.sample. The appended divisions does not seem to detect it.

What can I do to detect mouseover event for the appended divisions?

Ernest Soo
  • 193
  • 2
  • 13
  • use `.on()` delegate the event like `$('#append').on('mouseenter','.sample'.function(){})` – guradio May 18 '17 at 08:45
  • You need live event. Right now all events attached after page init don't have event listener on them. Like guradio says you ca use `.on()` and event listener will be created automatic when new element is added to the DOM. – Petroff May 18 '17 at 08:47

1 Answers1

1

You can use following script for this

$(document).on("mouseenter", "div.sample", function(){
    alert("Mouse Enter Event Detected");
});
Super User
  • 8,642
  • 3
  • 24
  • 43