I'd like to create a javascript mousedown event handler for a button. While the button is depressed, I need the handler to execute repeatedly until the button is released (mouseup is fired). E.g. holding an Up button should cause a text box value to increment until it is released.
What's the best way to handle this?
You can make use of setInterval: http://jsfiddle.net/5wypC/1/.
var interval = null;
var i = 0;
$('button').mousedown(function() {
clearInterval(interval); // Make sure to clear any intervals
// that are occasionally still running
interval = setInterval(function() {
$('textarea').val(i++);
}, 100);
});
$('button').mouseup(function() {
clearInterval(interval);
});
Related
How to trigger a mouse click on the element (slider "next" button) each X seconds?
I have built a website in Adobe Muse, but the slider widget doesn’t have an auto play function, and I’m trying to make the next button click each 5 seconds to simulate autoplay. I’ve found the class for the button
<div class="fp-controlArrow fp-next"></div>
maybe there is even a chance to trigger clicking it somehow? Thanks
I had to specify both classes to trigger the button and use a bit more difficult command. This worked:
var interval = setInterval(function() {
document.querySelector('.fp-controlArrow.fp-next').click();
}, 5000);
Now I have additional question: is it possible to stop clicking after user will click either back or next button with a mouse?
As a half-measure I’ve set it to stop at about a time it returns to the first slide but it would be much better to stop it after user clicks any of the button...
var interval = setInterval(function() {
document.querySelector('.fp-controlArrow.fp-next').click();
}, 7000);
setTimeout(function( ) { clearInterval( interval ); }, 44000);
Thanks
Use setInterval():
setInterval(() => {
element.click()
}, 5000)
where element is a reference to your DOM element.
you can store your interval on a variable and stop it whenever you want
var interval = setInterval(function() {
button.click();
// [button] here is the element you found with the specified class
// if you're using jQuery
// you can get you button and trigger the event
// beware of other buttons using the same class
jQuery(".fp-next").trigger("click");
}, 5000);
//if you want to stop it
clearInterval(interval);
Need your valuable feedback on this. I have implemented idletimeout functionalty so that session will expire in 3 minutes if the user is idle.
In three scenario, I am resetting the timer.
On click or tap
after 2 seconds while processing is in progress
on scroll or scrollstart
The problem is sometimes session is getting timeout before the 3 minutes even if I tap, click or scroll and user is redirected to login page even if the function is gets called on tap click or scroll and resettimers is getting called. I am facing a bit hard time to figure out the loophole.
I am posting the code; please let me know if you notice anything.
// Set timeout variables.
var timoutNow = 180000 ;
var ua = navigator.userAgent;
var event = ((ua.match(/iPad/i)) || (ua.match(/iPhone/i)) || (ua.match(/iPod/i))) ? 'touchstart' : 'click';
var logoutUrl = Mobile+'/login.html'; // URL to logout page.
var timeoutTimer;
// Start timers.
function StartTimers() {
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
//console.log(timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(timeoutTimer);
StartTimers();
}
// Processing time check.
function Laodtimercheck()
{
setInterval(function(){
if($("body").hasClass("loading-processing")==true)
{
ResetTimers();
}
}, 2000);
}
// Logout the user.
function IdleTimeout() {
sessionStorage.clear();
document.location.href = Mobile+'/login.html';
}
$(document).live(event, function(){
//console.log("Reset timers: ON TAP OR CLICK");
ResetTimers();
});
$(document).mouseover(function() {
//console.log("Reset timers: ONMOUSEOVER");
ResetTimers();
});
$(window).scroll(function() {
//console.log("Reset timers: SCROLL");
ResetTimers();
});
$(document).live("scrollstart", function(){
//console.log("Reset timers: SCROLLSTART");
ResetTimers();
});
EDIT: setTimeout only working first two times; next time ResetTimers are getting invoked but the setTimeout is not working or I might be missing something here as the session is getting timed out as per pervious two call time only....
The real problem that you're having is the folowing: "ResetTimers" not being invoke enough.
Why is not being invoked enough? I'll try to answer that.
All the logic is Ok with a few exceptions. There are two "problematic" events that not work or I think don't work like you want.
1.- LIVE (event)
That event is not being fired never. You cannot attach a live event to a document, yo need to specify a node, like html or body.
$("body").live(event, function(){
//console.log("Reset timers: ON TAP OR CLICK");
ResetTimers();
});
That's why when clicked the timer don't reset.
Another (and recomended) way to use a variable for binding events is to use .delegate().
Since jQuery 1.4.3+ is the recomended way of doing this.
$(document).delegate("body", event, function(){
//console.log("Reset timers: ON TAP OR CLICK (delegate)");
ResetTimers();
});
Any of those (live on body or delegate) would work and timer get reset on click or tap event.
2.- MOUSEOVER
There isn't a problem per se with this event, but I think it would be insuficient. MouseOver only fires where the pointer get on screen first time, if the mouse don't leave the window the mouseover never fires again. Maybe, a better or added way of control "mouse hovering" on the document is to use onmousemove event. Like I said in a comment before, I don't know if you want to be strict on this, so I left you a proposal and let's see if it fits your needs.
$(document).mouseover(function() {
console.log("Reset timers: ONMOUSEOVER");
ResetTimers();
});
In my tests, events get fires a lot, and the timers get reset on each event without problems. I hope it helps you.
hI got a problem to use jQuery to recall afunction if window is on focus.
And when window is not on focus (onblur) so pause that function until window is on focus again.
Here is my code:
function functiondosomething (user_id) {
var myInterval;
var time_delay = 1000;
$(window).focus(function () {
setTimeout(function() { functiondosomething (user_id); }, time_delay);
}).blur(function () {
clearTimeout(myInterval); // Clearing interval on window blur
});
setTimeout(function() { functiondosomething (user_id); }, time_delay);// ## problem here
}
My problem is :
When I remove that line (which I marked problem here above.) the
function will not work at first time until I click out of window to
make it onblur and come back on focus again, so it starting to work.
If I let that line (which I marked problem here above.) be there,
the function could not pause, even I click out of window to make it
be onblur.
When I click onfocus it start working and stop. I have to click out
of window and focus the window again again and again. Something like it need to be activate by clicking out of window and clicking back to window again.
What should I do ?
I see a few problems here:
You're not setting myInterval so when you call clearTimeout(myInterval) it's not clearing anything.
You're using the same function to set up your listeners and call setTimeout recursively. This means your handlers are being set every time you recur, and the recursion means it will run whether the handlers run or not.
I think you need to separate things a bit:
function functiondosomething(user_id) {
// Do stuff...
}
function setupHandlers(user_id) {
var myInterval;
var time_delay = 1000;
function doSomethingWrapper() {
functiondosomething(user_id);
myInterval = setTimeout(doSomethingWrapper, time_delay);
}
$(window).focus(function () {
doSomethingWrapper();
}).blur(function () {
clearTimeout(myInterval); // Clearing interval on window blur
});
doSomethingWrapper();
};
Basically, I have this image with left and right arrow button. This image, by default is the first frame I have extracted from some gif, the original gif contains 31 frames. My goal is when the users clicks the right arrow button, I want to display the next frame and so on... Everything is working perfectly as shown below code. However, I need to add some mousehold event so that when the user click and hold the mouse, I want to keep firing the next images. How can I achieve this?
$('#arrow_right').click(function (event) {
event.preventDefault();
var data_id = parseInt($(this).parent().find('#inner_wrap img').attr('data-id'));
if (data_id >= 1 && data_id <= 30) {
data_id = data_id + 1;
var avatar_num = $('#inner_wrap').html('<img id="avatar" data-id="' + data_id + '" src="img/avatar_test' + data_id + '.gif" width="90" height="200">');
}
});
Well you can use the mousedown event to start a function that displays the gif-frame: http://api.jquery.com/mousedown/ and then add another event handler for the mouseup event that will stop that function. That function can be called via setInterval() in the mousedown-event for example and get stopped via clearInterval() in the mouseup event.
This is an example that shows the principle:
var interval;
$(button).addEventListener('mousedown',function(e) {
interval = setInterval(function() {
// here goes your code that displays your image/replaces the one that is already there
},500); // 500ms between each frame
});
$(button).addEventListener('mouseup',function(e) {
clearInterval(interval);
});
// Thank you, Timo002, for your contribution!
// This code will stop the interval if you move your mouse away from the button while still holding it.
$(button).addEventListener('mouseout',function(e) {
clearInterval(interval);
});
In addition of the answer of Zim84, I should also add this piece of code!
$(button).addEventListener('mouseout',function(e) {
clearInterval(interval);
});
This will take care that if someone pushes the button (mousedown) and holds its mouse down and leaves (mouseout) the button, the interval is also cleared. Without this the interval does not stop in this particularly situation.
I am using this code to dynamically change the text of a span element. It works in chrome, only changing the content of the span once, but does an infinite loop in IE (the count keeps updating and the html text keeps changing). Anyone know how I can fix it or why its happening?
bindFlagUpdate();
function bindFlagUpdate(){
$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
var string = $('#like-' + data.contentId).html();
var getNum = string.match(/[0-9]+/g);
var count = getNum[0];
if(data.flagStatus == 'flagged') {
count++;
} else {
count--;
}
$('#like-' + data.contentId).html("1 user likes this");
$(document).unbind();
bindFlagUpdate();
return false;
});
}
Description of the event:
The flagGlobalAfterLinkUpdate event This event is triggered
immediately after a flag link has been updated. (Flag links appear in
two flavors: "Bookmark this!" and "Unbookmark this!", and when we
speak of "update" we mean this change in appearance).
The even is attached to a "flag" button
To answer this we need to know more about the event flagGlobalAfterLinkUpdate and how it is triggered. It sounds like something in the callback function for the event is triggering the event, so once it's triggered once, it triggers itself continuously.