1
votes

I have multiple images (created dynamically) in a div, I am applying mouseenter and mouseleave event for each image but its not working.

These images are blend image.

I want to display a cross button on image on mouseenter of image and hide cross button on mouseleave.

Below is my code :

Created dynamic html like this and appended it into a div:

<img src='images/box_bg.png' id='img"+finaldivId+"'/><ImageButton id='close" +   finaldivId + "'>Delete</ImageButton>    

Image blending code :

var id = "img" + finaldivId;
$('.ss-dragged-child img').blend({ id : id, mode: 'overlay', adjustment: 'rgb(' + colorArr.r + ',' + colorArr.g + ',' + colorArr.b + ')'});

Also I have returned img rather than canvas from blend.js and appended id in that img.

Below are mouseenter and mouseleave event on that img which is not working :

$('#img' + finaldivId).bind('mouseenter', function() {
     $("#close" + finaldivId).css({"display" : "block"});
});
$('#img' + finaldivId).bind('mouseleave', function() {
     $("#close" + finaldivId).css({"display" : "none"});
});

Kindly Suggest me the solution.

1

1 Answers

3
votes

Use delegation on() for dynamically appended html.

Demo Fiddle

$(document).on('mouseenter','img[id^="img"]', function() {
     $(this).next().css({"display" : "block"});
});
$(document).on('mouseleave','img[id^="img"]', function() {
     $(this).next().css({"display" : "none"});
});
  • img[id^="img"] checks img tags with Id - starting with 'img'.
  • $(this).next() finds next element/child of only the current <img>.

If the ID selector is important,

You have to explicitly call the bind() event everytime your append.