views:

73

answers:

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

+1  A: 

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: http://stackoverflow.com/questions/3563489/how-to-detect-inactive-tab-and-fill-it-with-color

Yi Jiang
Hi Yi Jiang! Thank you very much!
Peter
A: 

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

rem1x