Question

In this jsFiddle, despite what the jQuery docs say about .show() reverting CSS attributes to what they were, once .show(x).delay(x).hide(x) is called, the CSS hover code stops working:

Javascript:

$('.product').on('click', function(){
    $('.drawer').html("Something in your basket")
        .show(200).delay(500).hide(200);
});

CSS:

.drawer {
    border: 1px solid black;
    padding: 10px;
    position: absolute;
    top: 20px;
    left: 0px;
    display: none;
    width: 200px;
} 
.basket {
    position: relative;
}
.basket:hover .drawer {
    display: block;
}

HTML:

<div class="basket">
    <a href="#">Basket</a>
    <div class="drawer">No items in your basket</div>
</div>
<br/><br/><br/><br/><br/><br/>
<a href="#" class="product">Add X to basket</a>

What's going on here? I have only tested it in Firefox so far

Was it helpful?

Solution

jQuery does say it will revert the CSS attributes when you call .show(), but not .hide().

The documentation for .hide() says:

This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value.

If you .hide() and element first and then .show() it, jQuery will attempt to restore the original display value for the element. However, in your case you call in the order .show(x).delay(x).hide(x), with .hide() being the last function called which does not restore any values but merely applies .css("display", "none") on the element (and saves a value in case you call .show() later). The order matters.

Thus in this case you should use a complete callback function to remove the display attribute.

$('.product').on('click', function(){
    $('.drawer').html("Something in your basket")
        .show(200).delay(500).hide(200, function() {
            $(this).css("display", "");
        });
});

And it should work fine now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top