Chris
Chris

Reputation: 889

jQuery text fade after 30 second idle

I have this code to fade info text below some media after a 30 second initial delay. Once the mouse is moved, the info text snaps back to full opacity

setTimeout( '$(".media_info").animate({"opacity":".1"},5000)',30000);

$(document).mousemove(function() {
   $(".media_info").css('opacity','1');
});

Ideally, what I'd like to achieve is this: On page load, the mouse and scroll movements are monitored. If mouse and scroll have no input for 30 seconds, then the text would fade. Once the mouse or scroll is moved, the text goes back to full opacity, and the 30 second timer re-starts. Any ideas for the best way to achieve this? Any help would be much appreciated.

Upvotes: 2

Views: 1470

Answers (1)

Blazemonger
Blazemonger

Reputation: 92893

Clear the timer on mousemove or scroll, then re-start the timer:

function startTimer() {
    window.timer = setTimeout( function() {
        $(".media_info").animate({"opacity":0.1},5000);
    }, 30000);
};

$(document).on('scroll mousemove',function() { // 'keydown' as well?
    $(".media_info").stop().css({"opacity":1}); // stop the animation
    clearTimeout(window.timer);
    startTimer();
});
startTimer(); // start it now

Upvotes: 4

Related Questions