4

I would like to disable hover event on an anchor tag via jQuery for a certain interval.

example: I've got some CSS styles for a hover effect on anchor (< a href="">) element. When I hover the element I want it to wait certain time (500ms or so) and then to start rendering the hover effect.

Something like this maybe?

$("#navigation").hover(function () {
        $("li.has-submenu").off('hover');
        setTimeout(function () {
            $("li.has-submenu").on('hover');
        }, 1000);
    });
Václav Zeman
  • 606
  • 7
  • 21
  • Not a duplicate. This question has more solutions, not even related to JavaScript. – martynasma Jul 03 '15 at 12:42
  • For a plain CSS solution, you can use CSS3 transition as explained here : http://stackoverflow.com/questions/9393125/delay-mouseout-hover-with-css3-transitions – ben Jul 03 '15 at 12:45
  • Yes, I am aware of the CSS3 solution and for some reasons I cannot use that in my webpage. I need to completely disable hover event for some time. – Václav Zeman Jul 03 '15 at 12:50

2 Answers2

9

I checked recently, and it's 2015, this means that you can use CSS3 for this.

The following will start animating background color of all links after 500ms.

No jQuery or any JavaScript needed.

a {
  -webkit-transition: all 500ms ease-in;
  -moz-transition: all 500ms ease-in;
  -ms-transition: all 500ms ease-in;
  -o-transition: all 500ms ease-in;
  transition: all 500ms ease-in;
}

a:hover {
  background-color: #c00;    
  transition-delay: 500ms;
}
<a href="">Hover me</a>

If, however you absolutely need to do that with JavaScript, you can use setTimeout in to apply a hovered class to the element:

jQuery(function($) {
  $("a").hover(function() {
    var el = $(this);
    var timeout = setTimeout(function() {
      el.addClass("hover");
    }, 500);
    el.data("timeout", timeout);
  }, function() {
    clearTimeout($(this).removeClass("hover").data("timeout"));
  });
});
a {
  -webkit-transition: all 500ms ease-in;
  -moz-transition: all 500ms ease-in;
  -ms-transition: all 500ms ease-in;
  -o-transition: all 500ms ease-in;
  transition: all 500ms ease-in;
}

a.hover {
  background-color: #c00;    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="">Hover me</a>
martynasma
  • 8,542
  • 2
  • 28
  • 45
7

I guess you want something like this:

<div id='a' style="border:2px solid black" >
       <h3>Hove On me</h3>
           For 2000 milliseconds. You will get an alert.
       </br>
</div>




$(document).ready(function(){
   var delay=2000, setTimeoutConst;
   $('#a').hover(function(){
        setTimeoutConst = setTimeout(function(){
            /* Do Some Stuff*/
           alert('Thank You!');
        }, delay);
   },function(){
        clearTimeout(setTimeoutConst );
   })
})

DEMO: http://jsfiddle.net/faj81qa0/

PHP Worm...
  • 4,109
  • 1
  • 25
  • 48