Javascript popup when idle, only after a button is clicked - javascript

I'm trying to create a popup when a user is idle for (x) seconds and the idle timer only starts after a button is clicked but the timer is reset if there is mouse movement or another click. I also want this popup to only occur 1 timer per session.
So far I have the function working when the button is clicked and the popup shows up after 3 seconds. I would like the timer to be able to be reset when the mouse moves or is clicked.
Here's my javascript
function idlePop() {
var timer = 3000;
function resetTimer() {
}
$(document).ready(function() {
if (!sessionStorage.getItem('popupPreviouslyShown') || false) {
setTimeout(function() {
$('#donate-overlay').css('display', 'block');
sessionStorage.setItem('popupPreviouslyShown', true);
}, timer);
}
});
}
And the html button if you wanted to see it
<button onclick="idlePop();">Start</button>
I'm getting choked up on the function to reset the timer on mouse move (onmousemove) and on mouse click. Any help would be extremely appreciated.

i propose a solution , we'll see with what you say:
i suggest you to replace
<button onclick="idlePop();">Start</button>
by
<button id="start">Start</button>
user clicks on start button and after an idle of 3sec the popup appears
UPDATED V1.0
$(document).ready(function() {
var stage = 0;
var timer = 3000;
var timout = -1;
var isDetectionActivated = false;
$("#start").on('click', function(e) {
$("#start").prop("disabled", true);
//e.stopPropagation();
console.log("start");
idlePop();
})
function activateDetection() {
isDetectionActivated = true;
$(document).on("mousemove click", function(e) {
console.log("timeout aborted")
// you couldt test the type of event with e.type
clearTimeout(timout);
//console.log("you have moved or clicked", e.type);
//re-launch process
idlePop();
});
}
function desactivateDetection() {
$(document).off("mousemove click");
isDetectionActivated = false;
}
function idlePop() {
console.log("idlePop");
//for debuging
/*
timout = launchTimeout(timer);
return;
*/
if (!sessionStorage.getItem('popupPreviouslyShown') || false) {
timout = launchTimeout(timer);
}
}
function launchPopup() {
console.log("popup");
$('#donate-overlay').css('display', 'block');
sessionStorage.setItem('popupPreviouslyShown', true);
}
function launchTimeout() {
if (!isDetectionActivated) {
activateDetection();
}
console.log("timeout activated");
return setTimeout(function() {
console.log("timeout finished");
$("#start").prop("disabled", false);
clearTimeout(timout);
desactivateDetection();
launchPopup();
}, timer);
}
});

Related

Idle event on mouse move - how to create loop?

Im trying to create this kind of code on my website:
When user is idle div "#news-main-page" have to fade in and fade out every 15 seconds.
But when user moves mouse I want function to break.
When user break function when news-main-page is visible it stays visible,
when user break function when news-main-page is hidden it stays hidden.
How to achieve this?
Right now it work like this if user will start moving mouse after sometime idle, function still execute
Below is my code
jQuery(document).ready(function( $ ){
idleTimer = null;
idleState = false;
idleWait = 15000;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
$('#news-main-page').removeClass('d-none');
$("#news-main-page").delay(15000).fadeOut();
$("#news-main-page").delay(15000).fadeIn();
$("#news-main-page").delay(15000).fadeOut();
idleState = true; }, idleWait);
});
$("body").trigger("mousemove");
});
}) (jQuery)
});
Just call .stop() on news-main-page
$(document).ready(function () {
var myFunc =
function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
$('#news-main-page').removeClass('d-none');
$("#news-main-page").delay(15000).fadeOut();
$("#news-main-page").delay(15000).fadeIn();
$("#news-main-page").delay(15000).fadeOut();
idleState = true; }, idleWait);
});
$("body").mouseMove(function() {
$('*').unbind('mousemove keydown scroll',myFunc);
$("#news-main-page").stop();
});
});
$('*').bind('mousemove keydown scroll',myFunc);
}) (jQuery)

Check if mouse button is down on a button/picture and keep executing a function after every few seconds till the button is pressed?

Basically what I am trying to do is, I am trying to call a function and repeat the same function after every "n" seconds till the mouse button is pressed (MouseDown) on a button/picture and stop calling the function when the mouse button is released (MouseUp). I am trying to do this using JavaScript!
SOME REFERENCES
https://api.jquery.com/mousedown/
How can I detect a rightmouse button event on mousedown?
JavaScript: Check if mouse button down?
Not tested, but to give an idea.
var state = false;
function repeatingFunction(){
if (!state){
return;
}
console.log("Do something");
setTimeout(repeatingFunction, 2000);
}
function mymousedown(ev){
state = true;
repeatingFunction();
}
function mymouseup(ev){
state = false;
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", mymousedown);
obj.addEventListener("mouseup", mymouseup);
This should work for you:
var timerId = 0;
function onmousedown(ev) {
console.log("Do something"); //first call right after mouse down
timerId = setInterval(function () {
console.log("Do something");
}, 2000);
}
function onmouseup(ev) {
clearInterval(timerId);
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", onmousedown);
obj.addEventListener("mouseup", onmouseup);
fiddle: https://jsfiddle.net/kLnjh9zd/

Function works only in debugger

I wrote the function for check if button was clicked twice and if it was to measure the time between two clicks. It has to prevent multiple clicks in short time.
Button click:
$("#Save").click(function () {
dateTime1 = new Date().getTime();
BtnId = this.id;
showSaveDialog();
});
And measuring function:
ButtonWasTriggeredTwice: function () {
var result = false;
var currentTime = new Date().getTime();
var time = currentTime - dateTime1;
if (PreviousBtn === null) {
result= false;
} else {
if (PreviousBtn === BtnId) {
if ( time < 1500) {
result = true;
}
else result = false;
}
else {
result= false;
}
}
PreviousBtn = BtnId;
BtnId = null;
return result;
}
BtnId and PreviosusBtn are global scope variables.
The strange thing is this function works great when I set breakpoints in debugger. If I switch off debugger function blocks every next click on button, no matter what time interval is between clicks
You can use this solution with unbind and timeout, like this:
HTML
<input type="button" id="Save" value="save me" />
JS:
function saveEventButton(){
$("#Save").click(function () {
alert('saved!');
$("#Save").unbind('click');
setTimeout(function(){
saveEventButton();
}, 5000); // 5sec
});
}
saveEventButton();
This is the JSFiddle
UPDATE This solution is a mix from mine and Revish Patel solution
function disableTimeout(_this){
$(_this).prop('disabled','disabled');
setTimeout(function(){
$(_this).prop('disabled','');
}, 5000); // 5sec
}
$("#Save").click(function () {
alert('saved!');
disableTimeout(this);
});
This is the JSfiddle
You can also disable button when you first click is performed.
$(document).ready(function () {
$("#Save").click(function(){
$('#Save').prop('disabled','disabled');
// Perform your button click operation
});
});

Detect Mousemovent inside of blur function Jquery

I am trying to create a neat way to stop an AJAX called based upon if the browser is in focus, and if the mouse moves.. So here's what I want it to do:
If the user goes to a different tab in their browser, minimized the window, or goes somewhere else other than the web app, I want it to kill the AJAX calls in 1 minute. If the user moves the mouse anywhere in the web app, it should consider the user "focused" on the app, and thus continue the ajax calls. I put a timeout called "st" in there to take care of the "timeout" portion, but adding in a mouse detector is a little more advanced. Here's what I have:
var window_focus = true;
$(document).ready(function () {
$('#alertbox').click(function () {
$('#alertbox').slideUp("slow");
});
// Check focal point
$(window).focus(function () {
if (window_focus) {
return
}
window_focus = true;
waitForMsg();
}).blur(function () {
if (!window_focus) {
return
}
console.log('Init Suspension...');
// Set Timeout
$(function () {
st = setTimeout(function () {
clearTimeout(setTimeoutConst);
window_focus = false;
document.title = 'Timed Out | WEBSITE';
console.log('Suspended');
}, 60000);
});
});
waitForMsg();
});
I was going to try adding in something like this:
$(function () {
$().mousemove(function () {
console.log('Reinitialize');
clearTimeout(st);
waitForMsg();
});
});
But it didn't work. Thanks for your help.
http://jsfiddle.net/popnoodles/5mqMm/
You probably want this using .one(). This will see the mouse move, run your procedure and not run it again, until the window is reloaded or it's on another page.
Putting it inside of blur means blurring sets it up again.
}).blur(function () {
$(document).one('mousemove', function(){
// i react ONCE to the mouse being moved
console.log('Reinitialize');
clearTimeout(st);
waitForMsg();
// focus the window again as desired
$(window).trigger('focus');
});
if (!window_focus) {
return
}
console.log('Init Suspension...');
// Set Timeout
$(function () {
st = setTimeout(function () {
clearTimeout(setTimeoutConst);
window_focus = false;
document.title = 'Timed Out | WEBSITE';
console.log('Suspended');
}, 60000);
});
});
Try this jsfiddle
var window_focus = true, lastMouseMoveTime;
$(document).ready(function () {
lastMouseMoveTime = new Date().getTime();
$('#alertbox').click(function () {
$('#alertbox').slideUp("slow");
});
// Check focal point
$(window).focus(function () {
if (window_focus) {
return
}
window_focus = true;
waitForMsg();
}).blur(function () {
if (!window_focus) {
return
}
window_focus = false;
console.log('Init Suspension...');
// Set Timeout
});
waitForMsg();
$(document).mousemove(function(){
lastMouseMoveTime = new Date().getTime();
if(!window_focus ){
waitForMsg(); // restarting ajax if it stopped because of mousemove.
}
});
});
in your ajax call method
if( !window_focus){
if( new Date().getTime() - lastMouseMoveTime > 60*1000 ){
return;
}
}

Run mousedown event every 0.2s, until mouse up

I am trying to consecutively add +1 to the value of a text input field when the user clicks a button.
Simplified, my JQuery code is something like this:
$('#button').on({
mousedown : function () {
var value = $(this).val();
$(this).val(value + 1);
},
mouseup : function () {
//Some other stuff here
}
});
This works every time the user clicks the button.
What I want is if the user keeps the button pressed, the mousedown event to fire every 0.2s until he stops pressing (and than the mouseup event fires).
I figure this should somehow be done with setTimeout() but I would be glad if someone showed me how. Thanks.
Use setInterval and clearInterval:
var interval;
$('#button').on({
mousedown : function () {
var el = $(this);
el.val(parseInt(el.val(), 10) + 1);
interval = window.setInterval(function(){
el.val(parseInt(el.val(), 10) + 1);
}, 200);
},
mouseup : function () {
window.clearInterval(interval);
}
});
However, it's not possible to run as often as every 0.2 ms, I suppose that you mean every 0.2 seconds...
You can use setInterval to repeat the event after the mousedown code
var int = null;
$("#button").mousedown(function() {
// Start the timer on mousedown
int = setInterval(function() {
$("#button").val($("#button").val() + 1);
}, 2);
}).mouseup(function() {
// Stop the timer after mouse up
clearInterval(int);
int = null;
// Other code
});
You can achieve this like that:
$('#button').on({
mousedown: function () {
$(this).data('clicked', true);
var self = this;
var process = function() {
if ($(self).data('clicked')) {
console.log("process...");
setTimeout(process, 200);
}
};
process();
},
mouseup: function () {
$(this).data('clicked', false);
}
});

Categories