Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery setTimeout

I'd like to add a timeout to this tooltip code so it only displays if the mouse hovers over it after a while rather than immediately... I tried adding the setTimeout() but I could not figure out how to use the clearTimeout() so the tooltip does not hide on mouseout. Can you help?

// -----------------------------------------------
// TOOLTIP MOUSE HOVER
// -----------------------------------------------
function mcTooltip() {
    $('.mcTxb').mousemove(function(e) {
        var mcHoverText = $(this).attr('alt');
        var mcTooltip = $('.mcTooltip');
        $(mcTooltip).text(mcHoverText).show('fast');
        $(mcTooltip).css('top', e.clientY + 10).css('left', e.clientX + 10);
    }).mouseout(function() {
        var mcTooltip = $('.mcTooltip');
        $(mcTooltip).hide('fast');
    });
}
mcTooltip();

I tried this:

    // -----------------------------------------------
// TOOLTIP MOUSE HOVER
// -----------------------------------------------
function mcTooltip() {
    $('.mcTxb').mousemove(function(e) {
        var mcHoverText = $(this).attr('alt');
        var mcTooltip = $('.mcTooltip');
        setTimeOut(function(){
            $(mcTooltip).text(mcHoverText).show('fast');
        }, 300);
        $(mcTooltip).css('top', e.clientY + 10).css('left', e.clientX + 10);
    }).mouseout(function() {
        var mcTooltip = $('.mcTooltip');
        $(mcTooltip).hide('fast');
    });
}
mcTooltip();
like image 489
user1002039 Avatar asked Dec 22 '11 22:12

user1002039


2 Answers

As you're using animation, you can use .delay() to defer the appearance of your tooltip:

$(mcTooltip).text(mcHoverText).delay(1000).show('fast');

In your mouseout function, use .stop to cancel any existing delays or animations, and then hide the tooltip:

$(mcTooltip).stop(true).hide('fast');
like image 159
Alnitak Avatar answered Nov 07 '22 06:11

Alnitak


var my_timer;
$('.mcTxb').hover(
    function () {
        my_timer = setTimeout(function () {
            //do work here
        }, 500);
    },
    function () {
        clearTimeout(my_timer);
    }
);

This will wait half a second before doing whatever when you mouseover the element and the whatever will not happen if you mouseout within the half second.

like image 35
Jasper Avatar answered Nov 07 '22 04:11

Jasper