AK4668
AK4668

Reputation: 1912

jQuery autohide element after 5 seconds, if there is no mouse over

I am writing a shopping cart effect. When user add the product to shopping cart, the floating cart appears and hide in 5 seconds.

$("#cart").show().delay(5000).hide();

the problem is what if the user want to change something like quantity and the mouse is over the cart, obviously I don't want the cart to disappear when user mouse is over the cart.

Upvotes: 1

Views: 7703

Answers (3)

Pez Cuckow
Pez Cuckow

Reputation: 14412

Two main ways to approach this

Using a clearTimeout if the user mouses onto the item to stop the hide.

var countdown;

$("#cart").show().hover(function() {
    clearTimeout(countdown);
})

countdown = setTimeout(function() {
$('#cart').hide();
}, 5000);

Or

Using a boolean to decide whether or not to do the hide

mouseOver = false;
$("#cart").show(function() {
  setTimeout(function() {
    if (!mouseOver)
       $('#cart').hide();
   }, 5000)).hover(function() {
    mouseOver = true;
};

You could also (this makes the item fade unless they move the mouse over the item every 5 seconds):

var countdown;

$("#cart").show(resetCountdown).mousemove(resetCountdown);

function resetCountdown() {
   clearTimeout(countdown);
   countdown = setTimeout(function() {
      $('#cart').hide();
   }, 5000);
}

Upvotes: 7

GautamD31
GautamD31

Reputation: 28763

You can also try like this

$(document).ready(function(){
   $("#cart").show();
   $("#cart").delay(5000).hide();
});

or you can also edit like

$("#cart").hide('5000');

Upvotes: 0

Steven Hunt
Steven Hunt

Reputation: 2321

You could have a boolean value set to false, and then when you mouse over set it to true. Meanwhile, have a function defined using setTimeout:

setTimeout(function() {
if (!mybool)
$('#cart').hide();
}, 5000);

Upvotes: 0

Related Questions