JavaScript - Detect User Activity - Inactivity
JavaScript - Detect User Activity - Inactivity
This is a short guide on how to detect user activity or inactivity using JavaScript. To do this, we will capture
user events such as mouse movements, touch screen presses and keyboard presses.
There are a number of reasons why you might want to do this. The three reasons that immediately spring to
mind are:
1. You want JavaScript to log the user out after they’ve been inactive for too long. That or you want
to warn them that they are about to be logged out.
2. You want to pause a polling Ajax request.
3. There is an advert or a popup that you want to display if the user has been idle for a set period of
time.
In the code below, I will be using plain JavaScript as not everyone wants to have to include the entire
JQuery library for a small piece of functionality.
activityWatcher();
Code drilldown.
If you run the JavaScript function above, you should see something like this in your browser’s console:
The counter in the screenshot above was reset the first time after I moved my mouse. It reset the second
time when I pressed a key on my keyboard.
Activity events.
The code above uses five different types of events to determine user idleness. These are:
Note that these event handlers are applied to the document object, which represents the entire HTML
document that has been loaded into the browser.
This article was posted in Code, JavaScript, Tips & Tricks on May 30, 2019.