EnexoOnoma
EnexoOnoma

Reputation: 8836

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. However 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);
});

Upvotes: 2

Views: 315

Answers (2)

vzwick
vzwick

Reputation: 11044

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.

Upvotes: 1

Genjuro
Genjuro

Reputation: 7735

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

Upvotes: 0

Related Questions