Tag: mouse

LazyMouse jQuery Plugin – detect mouse inactivity easily :)

LazyMouse

Before jumping into the details, let me hear you asking “WHY?”. To be honest, not all of you will need to detect the mouse inactivity in your web applications. But sometime, it’s useful to do something different after a certain period of inactivity either to grab attention of the viewer, or to help him by improving the UX. For example, hide the sidebar and top navigation when user is reading the content, to emphasis his reading experience. Or show an animation – just do whatever during your user’s mouse is inactive for some time.

And to detect mouse inactivity easily, here comes the LazyMouse jQuery plugin which attaches two new events to the bodyelement, one is mouse.active and another one is mouse.inactive . You can just add two listeners for those events and do whatever you want to do 🙂

Using jQuery LazyMouse is pretty simple. Initialize it like this
[sourcecode language=”javascript”]
$(document).ready(function(){
$.LazyMouse();
})
[/sourcecode]

You can also specify the inactivity threshold in milliseconds, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$.LazyMouse({
delay:2000 //2 seconds threshold
});
})
[/sourcecode]

Once initialized, as we have mentioned earlier, the body element will be triggered with two new events. Lets add a listener to those, like this

[sourcecode language=”javascript”]
$(document).ready(function(){
$("body").bind("mouse.active",function(){
console.log("Mouse Active");
});
$("body").bind("mouse.inactive",function(){
console.log("Mouse Inctive");
});
})
[/sourcecode]

The events are propagated using jQuery Debounce, and therefore it is rate limited for good. See the live demo at http://hasinhayder.github.io/LazyMouse, and fork the github repo at http://github.com/hasinhayder/LazyMouse

Enjoy 🙂