Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hover event not working after append() div content

I am attempting to use jquery to append .thumb into another last div when click the .button

This is the jquery function:

$('.thumb').hover(function() {
    $(this).find('.close').fadeIn();
}, function() {
    $(this).find('.close').fadeOut();
});
$('.close').click(function() {
    $(this).parent().fadeOut('slow');
});
$('.button').click(function() {
    $html = '<div class="thumb">';
    $html += '<img src="http://findicons.com/files/icons/1979/social/50/wordpress.png" />';
    $html += '<div class="close">X</div>';
    $html += '</div>';
    $('.box').append($html);
});

http://jsfiddle.net/UfyQq/

The obstacle I am facing with this code is that the appended div not obey the hover event or use click function on the .close

I would really appreciate some help here, thanks!

like image 929
UserNaN Avatar asked Mar 06 '26 12:03

UserNaN


1 Answers

The problem is the appended content doesn't exist when you attach the event listeners. use jQuery's .on() on the parent element to fix this.

check this working jsFiddle

$('.box').on('mouseenter','.thumb',function() {
    $(this).find('.close').fadeIn();
});

$('.box').on('mouseleave','.thumb',function() {
    $(this).find('.close').fadeOut();
});
like image 104
Yotam Omer Avatar answered Mar 08 '26 21:03

Yotam Omer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!