I want to click a button on a page when it appears then wait a few seconds and click another button.
Relevant part of my code is below;
window.onload = function(){
if(document.getElementsByClassName("btnx").length>0){
document.getElementsByClassName("btnx")[0].click()
&(document.getElementsByClassName("btny")[0].click());
}
}
The problem is when it clicks the btnx it has to wait a few seconds till click btny but it click both almost at same time. Any advise about this will be great.
I figured it out, just keep my question here with it's answer to help aynone who search in future;
window.onload = function(){
if(document.getElementsByClassName("btnx").length>0){
document.getElementsByClassName("btnx")[0].click()
&setTimeout(function(){(document.getElementsByClassName("btny")[0].click())},3000);
}
}
Here is my version of solution for this
window.onload = function() {
let btnx = document.getElementsByClassName("btnx")[0];
let btny = document.getElementsByClassName("btny")[0];
btny.addEventListener("click", function() {
console.error("btny clicked");
});
btnx.addEventListener("click", function() {
console.error("btnx clicked");
setTimeout(function() {
btny.click();
}, 1000);
});
btnx.click();
};
Related
I have a function which will take some time to run on click event.
Following is merely an example and setTimeout is there only to simulate time it may take to run it. How can I ensure when a user click on an item any previous running function(s) is(are) cancelled and only the latest onclick function is fired?
i.e. if a user clicked on it 10 times. I want to only execute the only the 10th click not the 9 clicks before.
I am hoping for a pure/vanilla js solution... NOT jQuery
(function () {
var nav = document.querySelector('.nav__toggle');
var toggleState = function (elem, one, two) {
var elem = document.querySelector(elem);
elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one);
};
nav.onclick = function (e) {
setTimeout(function(){
toggleState('.nav ul', 'closed', 'open');
}, 5000);
e.preventDefault();
};
})();
fiddle: http://jsfiddle.net/6p94p48m/
You need to debounce your click handler.
var button = document.getElementById("debounced");
var clickHandler = function() {
alert('click handler');
}
var debounce = function(f, debounceTimeout) {
var to;
return function() {
clearTimeout(to);
to = setTimeout(f, debounceTimeout);
}
}
button.addEventListener('click', debounce(clickHandler, 5000));
<button id="debounced" href="#">debounced</button>
Or use underscore/lodash https://lodash.com/docs#debounce
I have already tried a lot, but did not come to an optimal solution. I have an image (html) and would like that if you press/click the image 5 seconds long, that he opens a link.
So far I have this code:
if (...) { window.location.href = 'http://www.google.com'; }
http://jsfiddle.net/xBz5k/
All the other answers open the link 5 seconds after a simple click. This one opens the link if the click lasted 5 seconds:
// the gif
var imgAnimation = '/images/animation.gif';
// the original image
var imgInitial = '/images/still.jpg';
// preload the gif
(new Image()).src = imgAnimation;
var imageMouseDown;
// mouse button gets pressed
$('#image').mousedown(function() {
$(this).prop('src', imgAnimation);
// start the timeout
imageMouseDown = setTimeout(function() {
window.location.href = 'http://www.google.com';
}, 5000);
});
// when the mouse button gets released
$('#image').mouseup(function() {
// the timeout isn't fired yet -> clear it
if (imageMouseDown) {
// set the old image again
$(this).prop('src', imgStill);
clearTimeout(imageMouseDown);
}
});
Here's a demo including the changing image: http://jsfiddle.net/7Qugn/
Use setTimeout in click event handler.
setTimeout should do the trick
Using jQuery:
$('#linkImg').click(function(){
setTimeout(function(){
window.location.href="http://google.com";
},5000);
});
Since this is a javascript answer, you could do:
document.getElementById('random-image').addEventListener('click', function() {
setTimeout(function(){
window.location.href = 'http://www.google.com';
}, 1000);
}, false);
I've created a JSFiddle for you (CLICK HERE), to illustrate the behavior.
This is the solution if you want to click and hold the image
var timeout = 0;
$('img').mousedown(function() {
timeout = setTimeout(myFunction, 5000);
}).bind('mouseup mouseleave', function() {
clearTimeout(timeout);
});
function myFunction() {
window.location.href="http://google.com";
}
How can I know how long a user has been holding the mouse button down (anywhere on a webpage)? I want to execute a function when the user held the mouse button for at least 2-3 seconds (preferably cancelling the mouse down in the process). Is this possible?
Here you go:
$(window).mousedown(function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
// do your thing
}, 2000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});
Live demo: http://jsfiddle.net/simevidas/Pe9sq/2/
Off hand I would experiment with $("body").mousedown(function(){}) using jQuery and $("body").mouseup(function(){}). I guess you can start a timer which will call function in 2 to 3 seconds. If the mouseup event occurs, then you can cancel the timer. You could probably test it with a simple script but you might have to look at cases where the click might have occurred because a link or button was clicked on the page. But as a starting point I would experiment with the $("body").mousedown and $("body").mouseup. If I have chance I'll see if I can send a code sample.
Try this:
function WhateverYoudLikeToExecWithinNext3Seconds(){
// Code goes here.
}
element.addEventListener('mousedown', function(){
setTimeout(function(){WhateverIdLikeToExecWithin3Seconds();}, 3000);
}, false);
Check out this one.
http://jsfiddle.net/b1Lzo60n/
Mousedown starts a timer that checks if mouse is still down after 1 second.
<button id="button">Press me</button>
<div id="log"></div>
Code:
var mousedown = false;
var mousedown_timer = '';
$('#button').mousedown(function(e) {
mousedown = true;
$('#log').text('mousedown...');
mousedown_timer = setTimeout(function() {
if(mousedown) {
$('#log').text('1 second');
}
}, 1000);
}).mouseup(function(e) {
mousedown = false;
clearTimeout(mousedown_timer);
$('#log').text('aborted');
});
I am trying to prevent duplicated data to database when the user click the submit button multiple times within a very short time (eg double click speed). First I disable the button after one click, then enable the button again after 3 seconds. I don't know why setTimeout("this.disabled=false",3000); is not working on jquery. Please help me out, below is my codes :
$(function() {
$(".btnSendResp").click(function() {
this.disabled = true;
setTimeout("this.disabled=false",3000);
postinResp();
});
});
You have the wrong this.
You need to save a reference to this in a local variable, then pass a function to setTimeout that uses the variable.
For example:
var self = this;
setTimeout(function() {
self.disabled = false;
}, 3000);
$(function() {
$(".btnSendResp").click(function() {
var that = this;
that.disabled = true;
setTimeout(function(){
that.disabled=false;
},3000);
postinResp();
});
});
I have an element on my page that I need to attach onclick and ondblclick event handlers to. When a single click happens, it should do something different than a double-click. When I first started trying to make this work, my head started spinning. Obviously, onclick will always fire when you double-click. So I tried using a timeout-based structure like this...
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
el.onclick = function() {
timer = setTimeout(function() { alert('Single'); }, 150);
}
el.ondblclick = function() {
clearTimeout(timer);
alert('Double');
}
}
But I got inconsistent results (using IE8). It would work properly alot of times, but sometimes I would get the "Single" alert two times.
Has anybody done this before? Is there a more effective way?
Like Matt, I had a much better experience when I increased the timeout value slightly. Also, to mitigate the problem of single click firing twice (which I was unable to reproduce with the higher timer anyway), I added a line to the single click handler:
el.onclick = function() {
if (timer) clearTimeout(timer);
timer = setTimeout(function() { alert('Single'); }, 250);
}
This way, if click is already set to fire, it will clear itself to avoid duplicate 'Single' alerts.
If you're getting 2 alerts, it would seem your threshold for detecing a double click is too small. Try increasing 150 to 300ms.
Also - I'm not sure that you are guaranteed the order in which click and dblclick are fired. So, when your dblclick gets fired, it clears out the first click event, but if it fires before the second 'click' event, this second event will still fire on its own, and you'll end up with both a double click event firing and a single click event firing.
I see two possible solutions to this potential problem:
1) Set another timeout for actually firing the double-click event. Mark in your code that the double click event is about to fire. Then, when the 2nd 'single click' event fires, it can check on this state, and say "oops, dbl click pending, so I'll do nothing"
2) The second option is to swap your target functions out based on click events. It might look something like this:
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
var firing = false;
var singleClick = function(){
alert('Single');
};
var doubleClick = function(){
alert('Double');
};
var firingFunc = singleClick;
el.onclick = function() {
// Detect the 2nd single click event, so we can stop it
if(firing)
return;
firing = true;
timer = setTimeout(function() {
firingFunc();
// Always revert back to singleClick firing function
firingFunc = singleClick;
firing = false;
}, 150);
}
el.ondblclick = function() {
firingFunc = doubleClick;
// Now, when the original timeout of your single click finishes,
// firingFunc will be pointing to your doubleClick handler
}
}
Basically what is happening here is you let the original timeout you set continue. It will always call firingFunc(); The only thing that changes is what firingFunc() is actually pointing to. Once the double click is detected, it sets it to doubleClick. And then we always revert back to singleClick once the timeout expires.
We also have a "firing" variable in there so we know to intercept the 2nd single click event.
Another alternative is to ignore dblclick events entirely, and just detect it with the single clicks and the timer:
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
var firing = false;
var singleClick = function(){
alert('Single');
};
var doubleClick = function(){
alert('Double');
};
var firingFunc = singleClick;
el.onclick = function() {
// Detect the 2nd single click event, so we can set it to doubleClick
if(firing){
firingFunc = doubleClick;
return;
}
firing = true;
timer = setTimeout(function() {
firingFunc();
// Always revert back to singleClick firing function
firingFunc = singleClick;
firing = false;
}, 150);
}
}
This is untested :)
Simple:
obj.onclick=function(e){
if(obj.timerID){
clearTimeout(obj.timerID);
obj.timerID=null;
console.log("double")
}
else{
obj.timerID=setTimeout(function(){
obj.timerID=null;
console.log("single")
},250)}
}//onclick
Small fix
if(typeof dbtimer != "undefined"){
dbclearTimeout(timer);
timer = undefined;
//double click
}else{
dbtimer = setTimeout(function() {
dbtimer = undefined;
//single click
}, 250);
}
, cellclick :
function(){
setTimeout(function(){
if (this.dblclickchk) return;
setTimeout(function(){
click event......
},100);
},500);
}
, celldblclick :
function(){
setTimeout(function(){
this.dblclickchk = true;
setTimeout(function(){
dblclick event.....
},100);
setTimeout(function(){
this.dblclickchk = false;
},3000);
},1);
}
I found by accident that this works (it's a case with Bing Maps):
pushpin.clickTimer = -1;
Microsoft.Maps.Events.addHandler(pushpin, 'click', (pushpin) {
return function () {
if (pushpin.clickTimer == -1) {
pushpin.clickTimer = setTimeout((function (pushpin) {
return function () {
alert('Single Clic!');
pushpin.clickTimer = -1;
// single click handle code here
}
}(pushpin)), 300);
}
}
}(pushpin)));
Microsoft.Maps.Events.addHandler(pushpin, 'dblclick', (function (pushpin) {
return function () {
alert('Double Click!');
clearTimeout(pushpin.clickTimer);
pushpin.clickTimer = -1;
// double click handle here
}
}(pushpin)));
It looks like the click event masks the dblclick event, and this usage is clearing it when we add a timeout. So, hopefully, this will work also with non Bing Maps cases, after a slight adaptation, but I didn't try it.