Over a million developers have joined DZone.

LazyMouse jQuery Plugin: Easily Detect Mouse Inactvitiy

DZone 's Guide to

LazyMouse jQuery Plugin: Easily Detect Mouse Inactvitiy

· Web Dev Zone ·
Free Resource


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:


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

		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:

		console.log("Mouse Active");
		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 :)


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}