Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

LazyMouse jQuery Plugin: Easily Detect Mouse Inactvitiy

DZone's Guide to

LazyMouse jQuery Plugin: Easily Detect Mouse Inactvitiy

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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 :)

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}