2

I try to build a really simple screensaver, but it is not as easy as I thought.

My solution did not really work and it is IMHO really dirty.

Did anyone have a good clean idea? Maybe without a timeout?

HTML

<div id="screensaver" style="width:100%; height:100%; background-color:#000000; display:none;" > &nbsp; </div>

JS

  $('body').live('mousemove', function (e)
    {

      if (e.type == 'mousemove')
      {
        clearTimeout(s_saver);
        s_saver = setTimeout('$(\'#screensaver\').fadeIn();', 4000);
        $('#screensaver').hide();          
      }

    });  

http://jsfiddle.net/mwhJJ/4/

Thanks in advance!
Peter

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
Peter
  • 11,413
  • 31
  • 100
  • 152

2 Answers2

6

The main problem with your script is that the s_saver variable is not declared properly, and is in the wrong scope - you need it to still be read the next time the event handler is called, so you should declare it outside the scope of the handler. This should work (jsfiddle version):

var s_saver;

$('body').mousemove(function() {
    clearTimeout(s_saver);

    s_saver = setTimeout(function(){
        $('#screensaver').fadeIn(900);
    }, 4000);

    $('#screensaver').fadeOut(100);
});

Of course this is still dependent on what you want to achieve. If, for instance, you want to show something while your user isn't looking at this particular tab/window instead of just not moving the mouse, then the solution provided in this question should do: How to detect inactive tab and fill it with color

Community
  • 1
  • 1
Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
  • Any way to start the timeout on load? When the page loads, the div is active and the screensaver is on until mouse is moved. –  Mar 01 '21 at 05:50
-2

Dont you think the browser will hang listening to contineous mouse move events....? not to demotivate you but just an idea.

rem1x
  • 1