Search code examples
javascriptjqueryfocusdelay

How can I delay focus event in jquery?


I have a few buttons on my page and I want to switch focus on each on of them with a certain delay. How I can achieve that with jquery or pure javascript. This is the idea I have for iterating along all my buttons but I obviously end up with the focus on my last button.

$(document).ready(function() {
var allButtons = $(":button");
for (i=0;i<=allButtons.length;i++) {
   $('.category_button')[i].focus()
}
});

Solution

  • You can do this by creating a closure within your for loop and passing the index to the setTimeout delay:

    var allButtons = $(":button");
    for (i = 0; i < allButtons.length; i++) {
        (function(index) {
            setTimeout(function() { 
                allButtons[index].focus(); 
            }, 1000*index);
        }(i));
    }
    

    See example here.