Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Fade object after 20 seconds of inactivity

I want to fade out a div if a user hasn't made a mouse click for 20 seconds.

I have the following code:

if($('.main-popup2').is(":visible")){
    setTimeout(function() {
        $('.main-popup2').fadeOut('fast');
    }, 20000);
}

Problem is I don't know how to reset the setTimeout after detecting a user mouse click.

Thanks!

like image 400
jribeiro Avatar asked Jan 18 '23 09:01

jribeiro


2 Answers

The .setTimeout() method actually returns a reference to the timer it creates. This reference can be used in .clearTimeout to stop the timer before it executes.

Here is an example of how to use this:

var timer;

if($('.main-popup2').is(":visible")){
    // create the timer and save its reference
    timer = setTimeout(function() {
        $('.main-popup2').fadeOut('fast');
    }, 20000);
}

// when clicking somewhere on the page, stop the timer
$(document).click(function() {
    clearTimeout(timer);
}):
like image 184
Didier Ghys Avatar answered Jan 20 '23 14:01

Didier Ghys


var timeout = null;
var fadeElement = $('.main-popup2');

function fader() {
    if(null !== timeout) {
        clearTimeout(timeout);
    }
    fadeElement.stop();
    timeout = setTimeout(function () {fadeElement.fadeOut('fast');}, 2000);
}

$(document).click(fader);
fader();
like image 43
silly Avatar answered Jan 20 '23 15:01

silly