0

So I am trying to achieve a popup situation, where the user will hover over one element, when the user hovers over this element, jQuery adds a class to another sibling element which makes it visible. When the user hovers out I'd like to add a delay of like 5 seconds before the class is removed again, but my attempts to do this have not worked out thus far, can anybody give me a pointer on what method I can use?

Here is the code I'm using at the moment:

$('.spaceship-container').hover(
function(){
    $('.take-me-to-your-newsletter').addClass('show')
},
function(){
    setTimeout(3000);
    $('.take-me-to-your-newsletter').removeClass('show')
}
);  
  • like this? $('.spaceship-container').hover( function(){ $('.take-me-to-your-newsletter').addClass('tmtyn') }, setTimeout(3000, function(){ $('.take-me-to-your-newsletter').removeClass('tmtyn') }); – Richard Grandi Sep 11 '15 at 13:33
  • possible duplicate of [JavaScript.setTimeout](http://stackoverflow.com/questions/10312963/javascript-settimeout) – D4V1D Sep 11 '15 at 13:35

2 Answers2

2

Using proper syntax of setTimeout() function fixes your issue. But you also need to stop mouseout function using clearTimeout().

var timer;
$('.spaceship-container').hover(
  function() {
    clearTimeout(timer);
    $('.take-me-to-your-newsletter').addClass('show');
  },
  function() {
    timer = setTimeout(function(){
        $('.take-me-to-your-newsletter').removeClass('show');
    }, 3000);
  }
);
rrk
  • 15,677
  • 4
  • 29
  • 45
  • 1
    Whilst this answer is also correct, I will elect the one by @Guruprasad-Rao correct due to adding a level of explanation in to the answer. Thank you. – Richard Grandi Sep 11 '15 at 13:38
  • 1
    @RichardGrandi. I agree with Rejith, you might want to clear the `timeout` again if you are allowing user to hover the element again, unless you cover the whole stuff with some overlay.. :) +1 for good thinking Rejith.. – Guruprasad J Rao Sep 11 '15 at 13:44
1

You need to add the removeClass inside the callback of setTimeout as below:

$('.spaceship-container').hover(
function(){
    $('.take-me-to-your-newsletter').addClass('show')
},
function(){
    setTimeout(function(){
         $('.take-me-to-your-newsletter').removeClass('show') //here
    },3000);
});  

So that once the 3 seconds time is completed, the lines inside the callback function will get executed.

Plus a DEMO for you

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200