Search code examples
javascriptdom-events

How To Alter This Code So That It Only Redirects If There Is No Mouse Movement


I have the following JavaScript which redirects the user to another website (Google in this case):

<script type="text/JavaScript">
window.setTimeout("location=('http://www.google.com');",5000);
</script>

However, although I want the website to redirect to another website, I don't want it to redirect for no reason. My aim is for the website to redirect automatically on the condition that the cursor hasn't been moved for a little while.

Is this possible?


Solution

  • Something like this should work, although on older MSIE you'd need to use their equivalent of addEventListener()

    var timer = null;
    
    function goAway() {
        clearTimeout(timer);
        timer = setTimeout(function() {
            window.location = 'http://www.google.com/';
        }, 5000);
    }
    
    window.addEventListener('mousemove', goAway, true);
    
    goAway();  // start the first timer off
    

    ​All it does is ensure that every time the mouse is moved the timer is cleared, and then started up again.

    Demo at http://jsfiddle.net/alnitak/sXwHY/, although cross frame security stops it working correctly there.