开发者

Modification to simple jQuery script to randomize text with timer

I am using a jQuery script that shows a random slogan from an array on page load. Howeve开发者_JS百科r I want this slogan to be changed every 6 sec. How can I do this?

This is a working fiddle and here is the code:

$(document).ready(function () {
    phrases = [
        "a creative Chicago design shop",
        "design is simple",
        "we build fine, fine things",
        "we love creating"
    ];

    var phrase = phrases[Math.floor(Math.random()*phrases.length)]
    $('#site').text(phrase);
});


Fiddle!

$(document).ready(function () {
    changePhrase();
    var rotate = setInterval(changePhrase, 6000);
});

function changePhrase() {
    phrases = [
        "a creative Chicago design shop",
        "design is simple",
        "we build fine, fine things",
        "we love creating"
    ];

    currentPhrase = $('#site').text();
    if (phrases.indexOf(currentPhrase)) phrases.splice(phrases.indexOf(currentPhrase), 1); // remove current phrase from array to prevent repetitions

    var phrase = phrases[Math.floor(Math.random()*phrases.length)]
    $('#site').text(phrase);
}

Update: Thrown in a two-liner that prevents repetition of the same phrase two times in a row for good measure.


this will change phrases for an infinite number of time , but you have to use the Jquery Timers Plugin .

$(document).everyTime(1000, function(i) {
  var phrase = phrases[Math.floor(Math.random()*phrases.length)]
$('#site').text(phrase);
}, 0);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜