after a few seconds an image has been clicked, open a link - javascript

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";
}

Related

Wait inside if command with Greasemonkey

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();
};

jQuery Fade object after 20 seconds of inactivity

I want to fade out a div if a user hasn't made a mouse click for 20 seconds.
I have the following code:
if($('.main-popup2').is(":visible")){
setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
Problem is I don't know how to reset the setTimeout after detecting a user mouse click.
Thanks!
The .setTimeout() method actually returns a reference to the timer it creates. This reference can be used in .clearTimeout to stop the timer before it executes.
Here is an example of how to use this:
var timer;
if($('.main-popup2').is(":visible")){
// create the timer and save its reference
timer = setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
// when clicking somewhere on the page, stop the timer
$(document).click(function() {
clearTimeout(timer);
}):
var timeout = null;
var fadeElement = $('.main-popup2');
function fader() {
if(null !== timeout) {
clearTimeout(timeout);
}
fadeElement.stop();
timeout = setTimeout(function () {fadeElement.fadeOut('fast');}, 2000);
}
$(document).click(fader);
fader();
Use delay function.
(window).click(function () {
$('.main-popup2').delay(6000).fadeOut(300);
}
Each click restart 6 seconds, after it .main-popup2 fadeout if there isn't

jquery/javascript blur/focus & settimeout

When mouse is over a product number (focus) then show some product information.
When user is not longer over a product number (blur), then wait 3 seconds, then hide details.
$('.productNumber').live('blur', function() {
setTimeout(function(){
var divToPutData = $(this);
divToPutData.hide();
}, 3000);
});
Now user says that if user moves mouse back within those 5 seconds to stop the count down, until a blur event fires again. No sure how to do this with setTimeout.
Use clearTimeout()
var myTimeout = null;
$('.productNumber').live('mouseover', function() {
//If timeout is still active, clear
if(myTimeout != null)
clearTimeout(myTimeout);
});
$('.productNumber').live('blur', function() {
//Store the ID returned by setTimeout
myTimout = setTimeout(function(){ divToPutData.hide(); }, 3000);
});
Use the function clearTimeout.
setTimeout returns a numeric id, you can store it in a variable, and then pass it to the clearTimeout function:
var myTimeout = setTimeout ( function(){alert(2);}, 1000);
clearTimeout(myTimeout);
var t;
$('.productNumber').live('mouseover', function() {
clearTimeout(t);
});
$('.productNumber').live('mouseout', function() {
t = setTimeout(function(){
divToPutData.hide();
}, 3000);
});
have the setTimeout assigned to a variable, so you can cancel it on hover again
var hideTimeout;
$('.productNumber').live('blur',function() {
hideTimeout = setTimeout(function() {
divToPutData.hide();
}, 3000);
});
$('.productNumber').live('mouseover',function() {
clearTimeout(hideTimeout);
// Do the show stuff
}
jQuery is not my strongest language, so you may need to modify this slightly, but this is the general approach to this scenario.
Use the jQuery stop() to abort any ongoing animation
Test it here: http://jsfiddle.net/T7kRr/1/
jQuery
$(".productNumber").hover(
function () {
$(this).find(".productDesc:last").stop(true, true).show();
},
function () {
$(this).find(".productDesc:last").delay(3000).fadeOut();
}
);
HTML
<div class="productNumber">1001<span class="productDesc" style="display:none">iPhone</span></div>
<div class="productNumber">2001<span class="productDesc" style="display:none">iPad</span></div>
<div class="productNumber">3333<span class="productDesc" style="display:none">TV</span></div>
<div class="productNumber">9999<span class="productDesc" style="display:none">HiFi</span></div>

Mousedown Timer using JavaScript/jQuery

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');
});

How to use both onclick and ondblclick on an element?

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.

Categories

Resources