Over a million developers have joined DZone.

LazyMouse jQuery Plugin: Easily Detect Mouse Inactvitiy

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

LazyMouse

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

To detect mouse inactivity easily, here is the LazyMouse jQuery plugin, which attaches two new events to the body element: 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:

$(document).ready(function(){
	$.LazyMouse();
})

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

$(document).ready(function(){
	$.LazyMouse({
		delay:2000 //2 seconds threshold
	});
})

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

$(document).ready(function(){
	$("body").bind("mouse.active",function(){
		console.log("Mouse Active");
	});
	$("body").bind("mouse.inactive",function(){
		console.log("Mouse Inctive");
	});
})

The events are propagated using jQuery Debounce, and therefore their 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 :)

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Hasin Hayder, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}