Hamdi Baligh
Hamdi Baligh

Reputation: 892

hover() function not working properly

I have a jQuery function that displays a pop-up menu when the div is hovered over:

<script type="text/javascript">   
    $('.thumbnail').hover(function (e) {
        $(this).children('.pop-up').show()
            .css('top', e.pageY + 20)
            .css('left', e.pageX + 10)
            .appendTo('body');
    }, function () {
        $(this).children('.pop-up').hide();
    });
</script>

The first function works well (the pop-up menu is displayed when the cursor is hover the div) but the second is not (the hide function)

Any ideas? Thank you

Edit

Here is my HTML Structure :

    <div class="thumbnail">
                            .........
<div class='pop-up'><h3>"@thumbnail.Forfait.Titre"</h3><p>"@thumbnail.Forfait.Description"</p></div>
</div>

Upvotes: 0

Views: 399

Answers (3)

Richard Dalton
Richard Dalton

Reputation: 35793

It's because you have appended the .pop-up elements to the body, so they are no longer children of the .thumbnail element.

Change the code in the second function to this and it should work:

$('body').children('.pop-up').hide().appendTo(this);

This assumes there are no other elements with a class of .pop-up

Edit - As mentioned by cfs in the comments. It is a good idea to re-append the pop-up to the thumbnail so it will still work on next hover.

Upvotes: 2

Didier Ghys
Didier Ghys

Reputation: 30666

Well, the .pop-up elements you select in the first handler are appended to the body element.

On the other handler, $(this).children('.pop-up') simply does not return any element anymore because they are not children anymore.

Upvotes: 1

Jason P
Jason P

Reputation: 27012

When you append the .pop-up to the body, it is no longer a child of the .thumbnail div, it is a child of the body, so

$(this).children('.pop-up').hide();

doesn't work.

Why are you appending to the body in the first place? It doesn't seem necessary.

Upvotes: 1

Related Questions