jribeiro
jribeiro

Reputation: 3463

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!

Upvotes: 4

Views: 2596

Answers (3)

Stefano Ciamma
Stefano Ciamma

Reputation: 11

Use delay function.

(window).click(function () {
   $('.main-popup2').delay(6000).fadeOut(300);
}

Each click restart 6 seconds, after it .main-popup2 fadeout if there isn't

Upvotes: 1

silly
silly

Reputation: 7887

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();

Upvotes: 1

Didier Ghys
Didier Ghys

Reputation: 30666

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);
}):

Upvotes: 7

Related Questions