最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I delay focus event in jquery? - Stack Overflow

programmeradmin0浏览0评论

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()
}
});

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()
}
});
Share Improve this question asked Mar 11, 2011 at 23:07 toplesstopless 8,23111 gold badges60 silver badges87 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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)

  1. 暂无评论