views:

70

answers:

4
$('.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?

+2  A: 

Do 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);
    });
});
Max Shawabkeh
You rock, thanks
The Guy
`setInterval(button.click)` works on its own, right? No reason to wrap in an extra function
Isaac Cambron
icambron, right you are.
Max Shawabkeh
+1  A: 
$(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);
    });
});
prodigitalson
+1  A: 

What about this?

setInterval(function(){ $('.button').click();},500);
Mike Sherov
It's best to not have to search the DOM every 500ms. I suggest saving off `$('.button')` into a variable, and just using that.
Justin Johnson
Great point, thanks for the help.
The Guy
+1  A: 

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
};
CMS
I really like this concept, it's reusable. The only thing is that it skips the first button, i.e. it clicks all the buttons except the first one.
The Guy
I set var i = -1; and it worked like a charm, thanks again
The Guy
It should with `var i = 0;` check this example: http://jsbin.com/ezuwe
CMS
I think it may be with how I tested it, your example seems to work fine. I put this after your code:$('.button').click(function(){ $(this).css('color','green'); });and only the last 4 buttons out of 5 changed to green. Now, I am trying to figure out why.
The Guy
Do you have any idea why?
The Guy