Search code examples
jqueryhoverdelay

delay hover method


hi guys i would like to delay hover method in this function

$(document).ready(function(){
$(".wypWedkarskie li").filter(":odd").hide().end().filter(":even").hover(
  function () {
    $(this).toggleClass("active")
      .next().stop(true, true).slideToggle();
  });
});

what i need to do ??


Solution

  • If you want to delay an action within a hover, you can use javascripts .setTimeout() to add a delay of x seconds.

    Try this, it will hide all odd items in a list, then add a hover effect to all the even ones, upon hovering it will instantly toggle the active class, and after two seconds it will toggle the next object:

    $(".wypWedkarskie li").filter(":odd").hide().end().filter(":even").hover(
        function() {
            var obj = $(this);
            var nextObj = obj.next();
    
            obj.toggleClass("active");
            setTimeout(function() {
                nextObj.slideToggle();
            }, 2000);
        }
    );
    

    You can see a working demo here


    Update :

    This should give you what I believe you are after.
    It will highlight the item you are hovering over instantly. After 2 seconds, if you are still hovering it will show the 2nd item. As soon as you stop hovering it will hide the 2nd item. If you stop hovering before 2 seconds, the 2nd item won't be shown:

    $(".wypWedkarskie li").filter(":odd").hide().end().filter(":even").hover(
        function() {
            var obj = $(this);
            var nextObj = obj.next();
            obj.addClass("active");
            setTimeout(function() {
                if (obj.hasClass('active')) {
                    nextObj.slideDown();
                }
            }, 2000);
        },
        function() {
            var obj = $(this);
            var nextObj = obj.next();
            obj.removeClass('active');
            nextObj.slideUp();
        }
    );
    

    See a working demo here