Search code examples
javascriptcsstabshovermouseenter

How to Create a Tab Hover With Timer


It is as follows: (Hover by Mouse)

----------------
|    Tab 01    |    Tab 02     
-------------------------------
| Tab 01 - Active             |
|                             |
|                             |
-------------------------------

That first tab (Tab 01) is active, But when I move my mouse over the second tab (Tab 02):

               ----------------
     Tab 01    |    Tab 02    |
-------------------------------
| Tab 02 - Active             |
|                             |
|                             |
-------------------------------

The first tab should wait for 2 seconds before activating the second tab.

I adopted code given in this example: https://jsfiddle.net/QA5Zp/25/

I changed the code with the link above and it is as follows:

$('.tabbox').on('mouseenter', function(){
   $('.tabbox').removeClass('active');
    setTimeout(function(){ $(this).addClass('active'); } , 2000);
});

Hence when I go to the second fever (Hover by Mouse), It hides the content.

What could be the reason and what am I doing wrong?


Solution

  • When you leave a tab, the timeout has already started the countdown. You'll need to clear the timeout, when you leave the current tab, or move to another tab (fiddle):

    var timeout;
    
    $('.tabbox')
      .on('mouseleave', function() {
        clearTimeout(timeout);
      })
      .on('mouseenter', function() {
        var $this = $(this);
        clearTimeout(timeout);
        timeout = setTimeout(function() {
          $('.tabbox').removeClass('active');
          $this.addClass('active');
        }, 2000);
      });