开发者

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.leng开发者_StackOverflowth;i++) {
   $('.category_button')[i].focus()
}
});


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.


You can use setTimeout to call a function after a delay. The function can set the focus on your next button.

So pseudocode --

setTimeout(2000, focusOn(0));

// somewhere else
function focusOn(i) {
    $('.category_button')[i].focus();
    if (i + 1 < numButtons)
    {
        setTimeout(2000, focusOn(i + 1);
    }
}


var currentButtonIndex = 0;

function FocusButton()
{
   // focus current button index here
   // increment counter
   // some condition when to stop 
   // call FocusButton again with delay
   // window.setTimeout(FocusButton,1000);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜