UserNaN
UserNaN

Reputation: 137

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!

Upvotes: 3

Views: 7185

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

You have to use delegation:

DEMO

$('.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

JohnnyJS
JohnnyJS

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

Yotam Omer
Yotam Omer

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.

check this working jsFiddle

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

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

Upvotes: 4

Related Questions