$('.button').click();
The above code works great to click all buttons on the page at once, but I am trying to fire off clicks every half or second or so until the jQuery Object has looped i.e.
$(function(){
$('.button').each(function(){
setInterval('$(this).click()', 500);
});
});
Can some one tell me how I can do this? the above code obviously does not work. Am I missing something?
$('.button').click();
The above code works great to click all buttons on the page at once, but I am trying to fire off clicks every half or second or so until the jQuery Object has looped i.e.
$(function(){
$('.button').each(function(){
setInterval('$(this).click()', 500);
});
});
Can some one tell me how I can do this? the above code obviously does not work. Am I missing something?
Share Improve this question edited Jan 30, 2010 at 1:18 Justin Johnson 31.3k7 gold badges66 silver badges89 bronze badges asked Jan 30, 2010 at 0:41 The GuyThe Guy 1152 silver badges7 bronze badges 2- What do you mean by "until the jQuery Object has looped," what "jQuery object"? – Justin Johnson Commented Jan 30, 2010 at 1:26
- I am probably referring too it the wrong way. Is the $('.button') a jQuery object that is getting looped through with the each method? Please excuse my noobness. – The Guy Commented Jan 30, 2010 at 1:35
4 Answers
Reset to default 2Do not use strings in setInterval()
or setTimeout()
. Always pass function objects:
$(function() {
$('.button').each(function(){
var button = $(this);
setInterval(function() {button.click();}, 500);
});
});
EDIT: If all you want is to trigger a click, this can also be expressed more simply as (thanks icambron):
$(function() {
$('.button').each(function(){
setInterval($(this).click, 500);
});
});
What about this?
setInterval(function(){ $('.button').click();},500);
$(function(){
var buttons = $('.button');
var len = buttons.length;
var intr = new Array();
buttons.each(function(i){
var $this = $(this);
var timeClick = function(){
if(i < len ){
$this.click();
}
else{
clearInterval(intr[i]);
}
};
intr[i] = setInterval(timeClick, 500);
});
});
You could build a function to execute the clicks sequentially, a click every N
specified milliseconds timeout, iterating the matched elements one by one:
Usage:
clickQueue($('.button'), 500);
The function:
var clickQueue = function ($els, timeout) {
var n = $els.length, i = 0;
function click () { // internal function
$els.eq(i++).click(); // click the element and increment i
if (i < n){
setTimeout(click, timeout); // execute again if possible
}
}
click(); // invoke for first time
};