This is a fairly simple piece of code, however, I decided it was worth putting up on the site for everybody to see.
Anyway the code itself aims to fire a function when there has been no mouse movement for a predefined length of time and reset the count every time the mouse is moved.
code
The code is very simple, therefore, only the JavaScript is worth talking about for this example, so that is going to be the focus of this article. Have a look for yourself below.
Right then here we go:
JavaScript
var timeOut = ”;
function init() {
Event.observe(document.body, ‘mousemove’, resetIdle, true);
setIdle();
}
function onIdleFunction(){
alert(’Your browser has been idle for ‘ + (idleTime/1000) +’ seconds.’);
}
function resetIdle(){
window.clearTimeout( timeOut );
setIdle();
}
function setIdle(){
timeOut = window.setTimeout( "onIdleFunction()", idleTime );
}
Event.observe(window, ‘load’, init, false);
At the top of the code there is a variable called "idleTime", this variable sets the idle state time (in milliseconds) that the browser mouse be idble for, before firing the function. Change this as you wish.
Next we have the "init" function which is called on page load by an event listener at the bottom of the sample code. This itself sets a mouse move event listener (which resets the idle state when fired) on the document body and also calls the idle state function.
We then have an "onIdleFunction" which is where you put the code you wish to be fired when the page is idle. In this example we’re just alerting out that the page has been idle.
Finally we have two functions, resetIdle and setIdle, which really do exactly what it says on the tin. The first resets the idle state (on mouse movement) and the second sets the idle state.
Well that’s about it so have a look for yourself at the demo and code below.
demo
Feel free to view the Simple JavaScript Idle State using Prototype Demo.
download
Also please have a look at the Simple JavaScript Idle State using Prototype Code.
note
The Idle State at present only uses mouse movement for detect inactivity. This will be problematic when considering devices that do not have mice (as it will not work), however, the code can be easily adapted to check for other forms of activity.
It is also worth while mentioning that the mouse move event is applied to the document body and therefore you must make sure that the height and width of the body and html are set to 100% for this to work, otherwise the event listener will not work.


6 Comments Received
This is a really usefull code snipet. Thanks..
very cool. thank you.
cool.thank you
Very very nice !
Thanx
Pingback & Trackback
Leave A Reply