Reputation: 137
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);
});
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!
Upvotes: 3
Views: 7185
Reputation: 74420
You have to use delegation:
$('.box').on({
mouseenter: function () {
$(this).find('.close').fadeIn();
},
mouseleave: function () {
$(this).find('.close').fadeOut();
}
}, '.thumb');
$('.box').on('click','.close',function () {
$(this).parent().fadeOut('slow');
});
Upvotes: 2
Reputation: 1472
Alter:
$('.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);
});
To:
$('.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);
$('.thumb').hover(function() {
$(this).find('.close').fadeIn();
}, function() {
$(this).find('.close').fadeOut();
});
$('.close').click(function() {
$(this).parent().fadeOut('slow');
});
});
That will attach the events once again.
Upvotes: 0
Reputation: 15366
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.
$('.box').on('mouseenter','.thumb',function() {
$(this).find('.close').fadeIn();
});
$('.box').on('mouseleave','.thumb',function() {
$(this).find('.close').fadeOut();
});
Upvotes: 4