Nicky R.
Nicky R.

Reputation: 23

.hover() with jQuery works only one time

My content box is disabled, I try to enable it with .hover(), but the problem is that .hover() works only on the first hover, not every time; content box class is .dboxcontent:

$('div.conbox').hover(function () {
    var activeID = $(this).attr('id');
    $('#' + activeID + ' .dboxcontent').show();
}, function () {
    var activeID = $(this).attr('id');
    $('#' + activeID + ' .dboxcontent').remove();
});

jsfiddle example

Upvotes: 0

Views: 371

Answers (3)

Sergio
Sergio

Reputation: 28845

Use .hide() instead of .remove(),
otherwise you are removing the DOM element with class .dboxcontent inside that hovered element.

Like this:

$('div.conbox').hover(function () {
    $(this).find('.dboxcontent').show();
}, function () {
    $(this).find('.dboxcontent').hide();
});

Fiddle

Actually you don't need jQuery for this, just CSS is the best solution here.

.conbox:hover .dboxcontent {
    display: block;
}

Just CSS here

Upvotes: 5

turtlepick
turtlepick

Reputation: 2714

When you do a .remove() you are actually removing the HTML element from the DOM.

You should hide it instead.

I would rewrite your js this way:

                 $('div.conbox').hover(
                     function() {
                         $(this).find('.dboxcontent').show();
                     }, function() {
                         $(this).find('.dboxcontent').hide();
                     }
                 );

You don't need string concatenation there. You can use a .find() instead.

http://jsfiddle.net/qVuhh/9/

Upvotes: 1

Manolo
Manolo

Reputation: 26460

You need .hide() method: http://jsfiddle.net/qVuhh/10/

If you use the remove()method, the tag is removed.

Upvotes: 1

Related Questions