To achieve screensaver like behavior, I wrote Screensaver.js. Note that the script doesn’t show or display a screensaver itself. It simply lets you attach functions to a pair of events for when the user goes idle and when they return. I’m using it on a couple of pages to start/stop a slideshow. It’s perfect for toggling type of functions which make sense to fire when the user goes idle. Or how about preloading images only when the user is idle?
You use it by creating a new Screensaver object and simply attaching your show/hide functions to the onActive and onIdle events it fires. For example, let’s say you have a Lightbox type of element and want to display it when the user goes idle. You would do something like this:
// Lightbox pseudocode
var lightbox = new Lightbox();
// Screensaver
var moosaver = new Screensaver({
onIdle: lightbox.show,
onActive: lightbox.hide,
ttl: 15000 // 15 seconds till idle.
});
Download your own copy at the GitHub Repo or just copy and paste the code below. The repo has a bit of documentation if you need more info.
(function() {
Screensaver = new Class({
Implements: [Options, Events],
options: {/*
onActive: $empty,
onIdle: $empty,*/
events: ['click', 'keypress', 'mousemove', 'resize', 'scroll'],
target: window,
ttl: 10000
},
initialize: function(options) {
this.setOptions(options);
this.enabled = false;
var target = document.id(this.options.target);
this.options.events.each(function(ev) {
target.addEvent(ev, this.reset.bind(this));
}, this);
this.monitor();
},
monitor: function() {
this.timer = this.display.delay(this.options.ttl, this);
},
reset: function() {
$clear(this.timer);
if (this.enabled) {
this.fireEvent('active');
this.enabled = false;
}
this.monitor();
},
display: function() {
this.fireEvent('idle');
this.enabled = true;
}
});
Element.implement({
screensave: function(options) {
options.target = this;
return new Screensaver(options)
}
});
})();

© 2009