Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop an array on jquery

I've been trying to make a script to change the text of a span.

Admittedly I'm not fantastic with jQuery and have found a script. I've edited i but i cannot get the script to loop and i don't know where to even start. Any code hints or links to relevant documentation would be greatly appreciated.

Here's the jQuery so far:

function change() {
        $('#msg').html(options.pop()).fadeIn(750).delay(2000).fadeOut(750, change);
};

var options = [
    "Red Bull",
    "Smoke",
    "Babes",
    "css",
    "batman"
].reverse(); 
change();

And on jsfiddle: http://jsfiddle.net/5s8y3/214/

like image 824
Max Coates Avatar asked Nov 29 '25 16:11

Max Coates


1 Answers

Stop popping off the array and use an iterator instead.

var messages = ["Red Bull", "Smoke", "Babes", "css", "batman"],
    i = 0;

(function change() {
    var msg = messages[i > messages.length - 1 ? (i = 0) : i++];
    $("#msg").html(msg).fadeIn(750).delay(2000).fadeOut(750, change);
})();

JSFiddle

like image 80
adeneo Avatar answered Dec 01 '25 13:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!