I have a web application and when the user is logged in, I would like to display a popup after some time if the user doesn't do anything to warn him that he will be logged out soon.
So I used intervals and I reset it each time the user interacts :
$(this).mousedown(function () {
reset();
});
$(this).mousemove(function () {
reset();
});
$(this).scroll(function () {
reset();
});
$(this).mouseup(function () {
reset();
});
$(this).click(function () {
reset();
});
$(this).keypress(function () {
reset();
});
But in some case, the timer is not reset and the popup shows up when the user is still using the application, for example when scrolling in a div.
Do I have to add my reset function to all possible events in my application or is there a simpler way to detect any interaction ?
To cover all machine types (PC, Tablet/phone (touch device), PC without mouse..)
on the body tag add a reset for these events:
That should cover any activity, I believe
I agree with the answer above but in my case I don't have JQuery.
I also listen for touchstart and click. In addition I use debounce to wait for all interaction to stop for one seccond.
import _ from 'lodash';
let ListenForInteraction = function () {
let lastId = Date.now();
let callbacks = {};
this.onInteraction = (callback) => {
lastId++;
callbacks[++lastId] = callback;
return
};
this.handleInteraction = _.debounce(() => {
console.log('Interaction')
for (let i in callbacks) {
if (typeof callbacks[i] === 'function') {
callbacks[i]();
} else {
delete callbacks[i];
}
}
}, 1000);
document.body.addEventListener('mousemove', this.handleInteraction);
document.body.addEventListener('scroll', this.handleInteraction);
document.body.addEventListener('keydown', this.handleInteraction);
document.body.addEventListener('click', this.handleInteraction);
document.body.addEventListener('touchstart', this.handleInteraction);
};
let listenForInteraction = new ListenForInteraction();
export default listenForInteraction;
//USAGE
listenForInteraction.onInteraction(() => {
localStorage.last_interaction = Date.now();
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With