How to cancel timeout if user performs click - javascript

I want to display a pop-up window after 10 second if any other click event is not performed. i.e. I displayed the pop-up window after 10 as:
setTimeout( "jQuery('#rollup-page-Modal').modal('show');",10000 );
Now there are few pop-up windows which will be displayed once clicked as:
jQuery(".more-info").click(function(event){
jQuery("#more-info-modal").modal('show');
event.preventDefault();
});
jQuery(".call-now").click(function(event){
jQuery("#request-callback-modal").modal('show');
event.preventDefault();
});
jQuery(".popup-send-quote").click(function(){
jQuery("#request-callback-modal").modal('hide');
jQuery("#callback-thankyou-modal").modal('show');
});
Now I want, the first pop-up window (which will be displayed after 10 sec) should not be displayed if any other pop-up windows is displayed or any other click event is performed.

You should to store the id of the timeout in a variable, then you can use window.clearTimeout() to clear the timeout when a click happens in the document:
var timer = setTimeout( "jQuery('#rollup-page-Modal').modal('show');",10000 );
$(document).on("click",function(){
clearTimeout(timer);
});

Add a flag
var didClick = false;
jQuery(".more-info").click(function(event){
jQuery("#more-info-modal").modal('show');
event.preventDefault();
didClick = true;
});
jQuery(".call-now").click(function(event){
jQuery("#request-callback-modal").modal('show');
event.preventDefault();
didClick = true;
});
jQuery(".popup-send-quote").click(function(){
jQuery("#request-callback-modal").modal('hide');
jQuery("#callback-thankyou-modal").modal('show');
didClick = true;
});
then set it to false before timeout
didClick = false;
setTimeout(function() {
if (!didClick) {
jQuery('#rollup-page-Modal').modal('show');
}
},10000 );

first the timeout code:
var timeout = setTimeout( function () {
jQuery('#rollup-page-Modal').modal('show');
},10000 );
now that it's in a var you can cancel it elsewhere in the code:
jQuery(".more-info").click(function(event){
clearTimeout(timeout);
jQuery("#more-info-modal").modal('show');
event.preventDefault();
});
jQuery(".call-now").click(function(event){
clearTimeout(timeout);
jQuery("#request-callback-modal").modal('show');
event.preventDefault();
});
jQuery(".popup-send-quote").click(function(){
clearTimeout(timeout);
jQuery("#request-callback-modal").modal('hide');
jQuery("#callback-thankyou-modal").modal('show');
});

Related

check user is inactive show a popup and reset if he clicks on continue button javascript

Requirement :
If user is inactive then show a popup after 5 minutes. and if selected continue session the timer will reset for this and again check for the same.
If user haven't click any continue button then the page will refresh.
How do you want to check if they are inactive?
You can tie an event to both the keyboard and mouse and reset timer each time the mouse moves/clicks or keydown.
<body onmousemove = "canceltimer()"; onclick = "canceltimer()">
var tim = 0;
function reload ()
{
tim = setTimeout("location.reload(true);",180000); // 3 minutes
}
function canceltimer()
{
window.clearTimeout(tim); // cancel the timer on each mousemove/click
reload(); // and restart it
}
Using jQuery:
$(function() {
(function handleInactivity() {
var maxIdleTime = 5000; // 5 seconds
var timeout = setTimeout(displayPopup, maxIdleTime);
function resetTimer() {
console.log("Timer reset");
clearTimeout(timeout);
timeout = setTimeout(displayPopup, maxIdleTime);
}
function displayPopup() {
console.log("You're up");
// Display popup of your choice
}
$(document).on("mousemove", resetTimer);
$(document).on("mouseDown", resetTimer);
$(document).keypress(resetTimer);
})();
});
_inactiveUserPopUp = function(warningTime,PageReloadTimeAfterWaring){
var maxIdleTime = warningTime *1000,timeout,resetTimer,displayPopup,pageReload;
timeout = setTimeout(displayPopup, maxIdleTime);
resetTimer = function(){
// console.log("Timer reset");
clearTimeout(timeout);
timeout = setTimeout(displayPopup, maxIdleTime);
};
displayPopup = function(){
//console.log("You're up");
clearTimeout(timeout);
var reloadPage = setTimeout(pageReload, PageReloadTimeAfterWaring*1000);
$(".modalDialog").css({
"opacity": 1,
"display": "block"
});
$(".close").on("click", function() {
$(".modalDialog").css({
"opacity": 0,
"display": "none"
});
});
$("#extend-session").off().on("click", function() {
clearTimeout(reloadPage);
$(".modalDialog").css({
"opacity": 0,
"display": "none"
});
$.ajax({
url: $("#openModal").data("ajaxUrl"),
type: "POST",
data: {
activeUser: true
},
success: function(data) {
}
});
});
};
pageReload = function(){
//console.log("reload page now")
$(document).off("mousemove");
$(document).off("mouseDown");
$(document).off("keypress");
window.location.reload();
};
$(document).on("mousemove", resetTimer);
$(document).on("mouseDown", resetTimer);
$(document).keypress(resetTimer);
};

Prototype.js how to fix use of clearTimeout( )

I'm using Prototype.js to load an html element when the user performs a mouseover on certain list items. I'm using setTimeout() to load the content only if the mouse is still over the list item after a given amount of time. I want to use clearTimeout when the user performs a mouseout on the same list item.
clearTimeout() is not clearing my timeout. I am pretty sure this is because of a common variable scope issue hidden from me by my lack of familiarity with Prototype.js
Can someone point out the flaw in this code or determine what I need to add to make the clearTimeout() function work properly?
document.observe( 'dom:loaded', function() {
var timeout;
$$('.nav-primary li.category').each( function( item ) {
item.observe('mouseover', function(event) {
event.stopPropagation();
categoryId = event.currentTarget.id;
getCategoryBlurb(categoryId);
timeout = setTimeout( function() {
showCategoryInfo(categoryData, categoryId);
}, waitTime);
});
item.observe('mouseout', function(event) {
event.stopPropagation();
clearTimeout(timeout);
});
});
});
Updated Code
$$('.nav-primary li.category').each( function( item ) {
var timeout = null;
item.observe('mouseover', function(event) {
event.stopPropagation();
categoryId = event.currentTarget.id;
getCategoryBlurb(categoryId);
if( timeout === null ) {
timeout = setTimeout( function() {
showCategoryInfo(categoryData, categoryId);
}, waitTime);
}
console.log(timeout);
});
item.observe('mouseout', function(event) {
if( timeout !== null ) {
console.log(timeout);
clearTimeout(timeout);
timeout = null;
}
});
});
clear the timeout before you set it
if (timeout) { clearTimeout(timeout); }
timeout = setTimeout( function() { /* code here */ });

Button function if the button is pressed for 10 seconds? [duplicate]

This question already has answers here:
How can I listen for a click-and-hold in jQuery?
(8 answers)
Closed 8 years ago.
I'm trying to find a way to execute a button function only if the user pressed/clicked on the button for 10 seconds.
the normal button function is:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
so is there any way to count the seconds from the moment the user pressed on the button and KEPT pressing, (a continuous pressing without clicking not tapping), and when the seconds hits 10, the function will execute?
You'll need timers, set one when the mouse is held down, clear it when the mouse is released.
$( "#target" ).on({
mousedown: function() {
$(this).data('timer', setTimeout(function() {
foo();
}, 10000));
},
mouseup: function() {
clearTimeout( $(this).data('timer') );
}
});
FIDDLE
You have to use mousedown and mouse up instead of click event ,
var timeOut = 0;
$("#target").mousedown(function () {
clearTimeout(timeOut);
timeOut = setTimeout(function () {
console.log("Handler for .click() called.");
}, 10000);
});
$(document).mouseup(function () {
clearTimeout(timeOut);
console.log("stop");
})
DEMO
The jQuery LongPress plugin will handle this for you.
https://github.com/vaidik/jquery-longpress
You can set the delay parameter before your function executes.
JS
var threshold = 10000, timeOne, timeTwo;
$('#t10').mousedown(function(){
timeOne = new Date();
}).mouseup(function(){
timeTwo = new Date();
if(timeTwo - timeOne >= threshold){
alert('Do what you want');
timeOne = 0;
}else{
console.log('Released early');
}
});
HTMl
<button id="t10">XX</button>
Fiddle
http://jsfiddle.net/5z94y2z5/
you needs to use mousedown and mouseup events
http://api.jquery.com/mousedown/
http://api.jquery.com/mouseup/
var pressedtensecondos = false;
var timer = null;
$( "#target" ).mousedown(function() {
timer = setTimeout(function() { pressedtensecondos = true; }, 10000);
});
$( "#target" ).mouseup(function() {
clearTimeout(timer);
if(pressedtensecondos)
alert('ten seconds');
pressedtensecondos = false;
});

Jquery: mousedown effect (while left click is held down)

I need a function that executes a function while a button is pressed and stops executing when the button is let go
$('#button').--while being held down--(function() {
//execute continuously
});
I believe something like this would work:
var timeout, clicker = $('#clicker');
clicker.mousedown(function(){
timeout = setInterval(function(){
// Do something continuously
}, 500);
return false;
});
$(document).mouseup(function(){
clearInterval(timeout);
return false;
});
See this demo: http://jsfiddle.net/8FmRd/
A small modification to the original answer:
$('#Clicker').mousedown(function () {
//do something here
timeout = setInterval(function () {
//do same thing here again
}, 500);
return false;
});
$('#Clicker').mouseup(function () {
clearInterval(timeout);
return false;
});
$('#Clicker').mouseout(function () {
clearInterval(timeout);
return false;
});
With the mouseout event on the Clicker it stops when you move your mouse out of the click area.
The reason why I suggest to do the same thing twice is to get a smoother effect. If you don't do it once before the timeout is set it will be a delay of, in this case, 500ms before something happens.
Here's a pure JavaScript implementation of the supplied solutions which has extended support for touch screens. You supply the id, action to perform (function(){}) and the interval (ms) to repeat the action. Note that this implementation will also execute the action immediately, rather than waiting for the interval to lapse.
// Configures an element to execute a function periodically whilst it holds the user's attention via a mouse press and hold.
function assertPeriodicPress(id, action, interval) {
// Listen for the MouseDown event.
document.getElementById(id).addEventListener('mousedown', function(ev) { action(); timeout = setInterval(action, interval); return false; }, false);
// Listen for mouse up events.
document.getElementById(id).addEventListener('mouseup', function(ev) { clearInterval(timeout); return false; }, false);
// Listen out for touch end events.
document.getElementById(id).addEventListener('touchend', function(ev) { clearInterval(timeout); return false; }, false);
}
$.fn.click2=function(cb,interval){
var timeout;
if(!interval) interval=100;
$(this).mousedown(function () {
var target=this;
timeout = setInterval(function(){
cb.apply(target);
}, interval);
return false;
}).mouseup(function () {
clearInterval(timeout);
return false;
}).mouseout(function () {
clearInterval(timeout);
return false;
});
}

Changing HTML on click in D3.js disables doubleclick [duplicate]

I've toggled click event to a node and I want to toggle a dbclick event to it as well. However it only triggers the click event when I dbclick on it.
So How do I set both events at the same time?
You have to do your "own" doubleclick detection
Something like that could work:
var clickedOnce = false;
var timer;
$("#test").bind("click", function(){
if (clickedOnce) {
run_on_double_click();
} else {
timer = setTimeout(function() {
run_on_simple_click(parameter);
}, 150);
clickedOnce = true;
}
});
function run_on_simple_click(parameter) {
alert(parameter);
alert("simpleclick");
clickedOnce = false;
}
function run_on_double_click() {
clickedOnce = false;
clearTimeout(timer);
alert("doubleclick");
}
Here is a working JSFiddle
For more information about what delay you should use for your timer, have a look here : How to use both onclick and ondblclick on an element?
$("#test-id").bind("click dblclick", function(){alert("hello")});
Works for both click and dblclick
EDIT --
I think its not possible. I was trying something like this.
$("#test").bind({
dblclick: function(){alert("Hii")},
mousedown: function(){alert("hello")}
});
But its not possible to reach double click without going through single click. I tried mouse down but it does not give any solution.
I pretty much used the same logic as Jeremy D.
However, in my case, it was more neat to solve this thing with anonymous functions, and a little slower double click timeout:
dblclick_timer = false
.on("click", function(d) {
// if double click timer is active, this click is the double click
if ( dblclick_timer )
{
clearTimeout(dblclick_timer)
dblclick_timer = false
// double click code code comes here
console.log("double click fired")
}
// otherwise, what to do after single click (double click has timed out)
else dblclick_timer = setTimeout( function(){
dblclick_timer = false
// single click code code comes here
console.log("single click fired")
}, 250)
})
you need to track double click and if its not a double click perform click action.
Try this
<p id="demo"></p>
<button id='btn'>Click and DoubleClick</button>
<script>
var doubleclick =false;
var clicktimeoutid = 0;
var dblclicktimeoutid = 0;
var clickcheck = function(e){
if(!clicktimeoutid)
clicktimeoutid = setTimeout(function(){
if(!doubleclick)
performclick(e);
clicktimeoutid =0;
},300);
}
var performclick =function(e){
document.getElementById("demo").innerHTML += 'click';
}
var performdblclick = function(e)
{
doubleclick = true;
document.getElementById("demo").innerHTML += 'dblclick';
dblclicktimeoutid = setTimeout(function(){doubleclick = false},800);
};
document.getElementById("btn").ondblclick = performdblclick;
document.getElementById("btn").onclick=clickcheck;
</script>
a slightly different approach - The actual click comparison happens later in the timeOut function, after a preset interval... till then we simply keep tab on the flags.
& with some simple modifications (click-counter instead of flags) it can also be extended to any number of rapid successive clicks (triple click, et al), limited by practicality.
var clicked = false,
dblClicked = false,
clickTimer;
function onClick(param){
console.log('Node clicked. param - ',param);
};
function onDoubleClick(param){
console.log('Node Double clicked. param - ',param);
};
function clickCheck(param){
if (!clicked){
clicked = true;
clickTimer = setTimeout(function(){
if(dblClicked){
onDoubleClick(param);
}
else if(clicked){
onClick(param);
}
clicked = false;
dblClicked = false;
clearTimeout(clickTimer);
},150);
} else {
dblClicked = true;
}
};

Categories

Resources