Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delay mouseenter event and raise event if mouse inside the element

I use this tab view that developed base on jQuery:

https://d2o0t5hpnwv4c1.cloudfront.net/001_Tabbed/site/jQuery.html#

I change the code that tabs change by mouseenter event. and I want to delay execution of the mouseenter event so if mouse enter the elemnt and remain there for portion of time mouseenter executes else (if mouse go outside in time less that that portion of time) mouseenter does not execute.I write this code:

$(document).ready(function () {
        $('a.tab').on('mouseenter', function () {
            var thisElement = $(this);
            setTimeout(function () {
                $(".active").removeClass("active");
                thisElement.addClass("active");
                $(".content").slideUp();
                var content_show = thisElement.attr("title");
                $("#" + content_show).slideDown();
            }, 300);
        });
    }); 

but if I bring mouse out of element mouseenter excecutes.How to solve this problem?

thanks

like image 976
Arian Avatar asked Oct 21 '25 04:10

Arian


1 Answers

You need to store the timeout handle and cancel it on mouseleave:

var timeout; 

$(document).ready(function () {
    $('a.tab').on('mouseenter', function () {
        var thisElement = $(this);

        if (timeout != null) { clearTimeout(timeout); }

        timeout = setTimeout(function () {
            $(".active").removeClass("active");
            thisElement.addClass("active");
            $(".content").slideUp();
            var content_show = thisElement.attr("title");
            $("#" + content_show).slideDown();
        }, 300);
    });

    $('a.tab').on('mouseleave', function () {
        if (timeout != null) { 
           clearTimeout(timeout); 

           timeout = null;
        }
    });
}); 
like image 189
Eben Roux Avatar answered Oct 23 '25 17:10

Eben Roux