this should be easy but I just can’t get it to work as it should… I have a div element serving as a button. I do not want the button to be visible all the time, just to appear when the user touches the screen (with finger or mouse), stays visible for a period of time (say 2 seconds) after inactivity and then disappear.
I do not want it to disappear 2 seconds after it was made visible (for that I could just use jQuery delay), I want it to disappear 2 seconds after the user has stopped interacting with the screen (i.e. the #grid element in my case). As long as the user is touching the screen or moving the mouse the button is visible, when he stops that activity 2 seconds passes and the button goes away.
The following I have, it does not work:
var grid = $('#grid');
grid.bind('mousemove touchmove tap swipeleft swipeup swipedown swiperight', function(e) {
var timer;
var circle= $('.circle-button');
if (!circle.is(":visible")) {
//button is not visible, fade in and tell it to fade out after 2s
$('.circle-button').fadeIn('slow');
timer = setTimeout(function(){ $('.circle-button').fadeOut('slow') }, 2000);
}
else {
//button is visible, need to increase timeout to 2s from now
if (timer) clearTimeout(timer);
timer = setTimeout(function(){ $('.circle-button').fadeOut('slow') }, 2000);
}
});
2
Answers
You can use code below.It might help:
Two issues:
var timer
is local to your event handler, which means that you will lose the identifier returned bysetTimeout
as soon as the execution of that event handler ends — which is immediate. You should make it a variable that has a longer lifetime.jQuery
bind
is deprecated (since 2016). Useon
instead.Here is a correction, with sample HTML to see it work: