开发者

How to change contents of a div based on timer

Is there any way in jquery to change the contents of a div based on timer.

Assume i have module to give "tips". The开发者_C百科 contents of the tips should change every 5 seconds.

Thanks


Make an array of tips. Then make a interval of 5 seconds that change the div's content. I assume you want random tips.

See this example on jsFiddle.

var tips = [
    "Tip 01",
    "Tip 02",
    "Tip 03",
    "Tip 04",
    "Tip 05",
    "Tip 06",
    "Tip 07",
    "Tip 08",
    "Tip 09"
];

// get a random index, get the value from array and
// change the div content
setInterval(function() {
    var i = Math.round((Math.random()) * tips.length);
    if (i == tips.length) --i;
    $("#tip").html(tips[i]);
}, 5 * 1000);

See:

  • setInterval
  • jQuery selectors
  • jQuery html


javascript has a method called .setInterval(), which will run code every n milliseconds.

var $div = $('#myDiv');

var timer = setInterval( function() {
    $div.html( newContent ); // which would reference some dynamic content 
}, 5000);

By storing the return value of .setInterval() in a variable, you can stop the interval later by using .clearInterval().

clearInterval( timer );
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜