Popup after user has been idle - javascript

I have written some code that brings up a message for the user to either ignore the message or go to another page if they have been idle for more than a minute. Everything works, as I want it to except when the user ignores the message. Here is my code:
if ( valid ) {
var idleTime = 0;
jQuery(document).ready(function () {
var idleInterval = setInterval(timerIncrement, 60000);
});
function resetTimer() {
idleTime = 0;
}
jQuery(document)
.on('mousemove', resetTimer)
.on('keydown', resetTimer)
.on('scroll', resetTimer);
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 1) {
jQuery('#popup').show();
}
jQuery(window).unbind();
}
jQuery('#popupClose').click(function() {
jQuery('#popup').hide();
});
}
I want the popup to not repopulate after they click #popupClose.

I'd do it like this. Just define a start time when you initialize your script. Let an interval run that checks how much time has passed. If it's more than your time wished show the dialog. if not hide it. Also reset the timer on your events.
Your javascript will look like this
$('#btclose').on('click', function(){
clearInterval(interv);
$('#popup').hide();
});
var start = new Date();
var interv = setInterval(function(){
var now = new Date();
console.log()
if(now-start > 5*1000){
$('#popup').show();
}
},10);
$('body').on('mousedown click mousemove', function(){
start = new Date();
});
Here's my fiddle
https://jsfiddle.net/c2L7wpn3/8/
Seems to work. Let me know if this helps

You can either store the information in a cookie, or with a flag (depending on whether you want the popup on each pageview or only once, period).
Then, check the flag/cookie before the showing of the popup. For example:
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 1) {
if (jQuery('#popup').data('closed') == 1){
jQuery('#popup').show();
}
}
jQuery(window).unbind();
}
jQuery('#popupClose').click(function() {
jQuery('#popup').data('closed', 1);
jQuery('#popup').hide();
});

Related

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

Javascript - page reload script won't work

I'm a complete newb to javascript, and much of this code was pulled from other sites. I'm trying to use two things I found to make a page redirect after the user is inactive for a specified amount of time.
I was able to get the timer working and make the page reload instead of redirecting, but my redirect code doesn't work for some reason.
EDIT: forgot to mention this code needs to work for specific pages, as I will be using one page to redirect to a specific page, and another to a different page.
jQuery(document).ready(function( $ ){
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 10000); // 10 seconds
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if ((idleTime > 0) && (window.location.pathname == '/wp')) { // 10 seconds
window.location.href = "https://www.google.com";
}
}
});
I tried you code, it works, but wrong. If it don't work for you - remove that && (window.location.pathname == '/wp') and try again. You have bigger problem, your code just redirects after 10 seconds no matter what. You need to replace to something like that:
jQuery(document).ready(function( $ ){
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if ((idleTime > 9) && (window.location.pathname == '/wp')) { // 10 seconds
window.location.href = "https://www.google.com";
}
}
});

How to reset session on keypress

I have implemented session timeout using setInterval() when the window loaded. How to reset session time on keypress event. Here is the code that I've written.
window.onload = function(){
(function(){
var counter = 60;
setInterval(function() {
counter--;
if (counter >= 0) {
//alert(counter)
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
$("#session-expired-modal").modal('show');
}
}, 1000);
})();
}
function sessionExpiredRedirect(){
window.location=url;
}
// Using jQuery (but could use pure JS with cross-browser event handlers):
var idleSeconds = 30;
$(function(){
var idleTimer;
function resetTimer(){
clearTimeout(idleTimer);
idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
}
$(document.body).bind('mousemove keydown click',resetTimer); //space separated events list that we want to monitor
resetTimer(); // Start the timer when the page loads
});
function whenUserIdle(){
//...your code
}

issue with if else conditional

When the page is open, it automatically set's a timeout to preform a task.
What i want is to change the timing if an event occur. If the user click a button, it changes the time right after the click.
If the user does nothing, the page should auto refresh after a given time, if the user click on "#b1" , the initial timeout should be interrupted and beggin a new one with other time set
I've tried the previous code, but it only executes the last alert .
How can i accomplish this ?
var clicked = 0;
var time = '';
$('#b1').click(function() {
clicked = 1;
});
if (clicked == 1) {
time = 10;
setTimeout(function() {
alert('clicked');
}, time);
} else {
time = 10000;
setTimeout(function() {
alert('nothingDone');
}, time);
}
Define a global variable where setTimeout is the value, call clearTimeout() with variable as parameter if user clicks #b1 element, then set variable to setTimeout() call within event handler
$(function() {
var clicked = 0;
var time = '';
var timer;
function updateTimer() {
time = 10;
timer = setTimeout(function() {
alert('clicked');
}, time);
}
$('#b1').click(function() {
clicked = 1;
clearTimeout(timer);
updateTimer()
});
if (clicked == 1) {
updateTimer()
} else {
time = 10000;
timer = setTimeout(function() {
alert('nothingDone');
}, time);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b1">click</div>

jquery fire event after timeout

I've implemented auto page scrolling using the jQuery plugin datatables.
I'm attempting to add two buttons, one that stops the auto scrolling and one that starts it again. I've gotten this working, but I want it to begin scrolling again if the page has been stopped for a period of time. Here is what I have tried:
var refreshRate = 5;
var totalPages = 0;
var currentPage = 0;
var upTime = 0;
$('document').ready(function(){
var interval = window.setInterval('$("#start").click()',refreshRate);
$("#start").click(function(){
function start(){
clearInterval(timeout);
$("#stop").show();
$("#start").hide();
currentPage = table.api().page.info().page + 1;
totalPages = table.api().page.info().pages;
table.api().ajax.reload(function(json){
if (currentPage != totalPages){
table.api().page('next').draw(false);
}
else{
table.api().page('first').draw(false);
}
});
upTime = upTime + (refreshRate / 1000);
clearInterval(interval);
interval = setInterval('$("#start").click()', refreshRate);
}
start();
});
$("#stop").click(function(){
$("#stop").hide();
$("#start").show();
timeout();
clearInterval(interval);
});
//call start on doc ready to auto start scrolling
start();
function timeout(){
var timeout = window.setInterval(function(){
start();
}, 10000);
}
});
As you can see I am attempting to call the start() function embedded within the button click after a 10 second timeout. I am also getting a TypeError when I call start() at DOM ready to begin page scrolling.
Uncaught TypeError: object is not a function
But besides the error it scrolls as it should.
Any assistance?
You are having issues with function scope. Your code that called start towards the bottom did not have start in its scope since you defined it inside the click handler. Also, timeout was outside of the scope too, which would cause the interval to go on forever:
$('document').ready(function(){
var timeout,
interval = window.setInterval('$("#start").click()',refreshRate);
function start(){
clearInterval(timeout);
$("#stop").show();
$("#start").hide();
currentPage = table.api().page.info().page + 1;
totalPages = table.api().page.info().pages;
table.api().ajax.reload(function(json){
if (currentPage != totalPages){
table.api().page('next').draw(false);
}
else{
table.api().page('first').draw(false);
}
});
upTime = upTime + (refreshRate / 1000);
clearInterval(interval);
interval = setInterval('$("#start").click()', refreshRate);
}
function timeout(){
timeout = setInterval(function(){
start();
}, 10000);
}
$("#start").click(function(){
start();
});
$("#stop").click(function(){
$("#stop").hide();
$("#start").show();
timeout();
clearInterval(interval);
});
//call start on doc ready to auto start scrolling
start();
});

Categories