Search code examples
jqueryfadeuser-inactivity

How do I fade out 1 div and fade in 2 divs, then after 10 seconds of inactivity, fade in the 1st div again, and fade the 2 divs out?


This is my code currently:

$(function() {          
        $('#header_left').click(function(){
            $('#header_left_info').fadeOut('fast');
            $('#header_left').fadeOut('fast');
            $('#header_left_back').delay(250).fadeIn('fast');
        });
});

(the 250 millisecond delay is so that the fades don't conflict)

Anyway, I'd like to modify this existing code so that it fades #header_left_back out, and #header_left back in - but only after 10 seconds of inactivity by the user. This should be simple, but for a web designer with no previous jQuery experience - it's really hard. Betcha you coders can figure this out within 20 seconds!

Thank you!

This question has been answered. Thanks!


Solution

  • I think you're after something like this:

    $(function() {          
      $('#header_left').click(function(){
        $('#header_left_info, #header_left').fadeOut('fast');
        $('#header_left_back').delay(250).fadeIn('fast');
      });
    
      var timer;
      $(document).bind("keypress mousemove", function() {
        clearTimeout(timer);
        timer = setTimeout(function() {
                  $('#header_left_back').fadeOut('fast', function() {
                    $('#header_left').fadeIn('fast');
                  });
                }, 10000);
      });
    });
    

    After 10 seconds of no mouse movement or keyboard action, it would go the fade in the reverse, swapping them back. You could add more events if needed, e.g. mousewheel, mousedown, as specific as you needed to be. Every time an event happens we start a 10 second countdown, if another event happens we clear the timeout and start the 10 seconds over, so only 10 seconds of idle makes the fades happen in reverse.