Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only display one array item at a time (Javascript)

I am trying to essentially create a ticker which shows a single string item taken from an array at a time. Basically I just want it to show a single item and then transition into the next, my Javascript skills are massively rudimentary (Jquery might be better for this.)

Here is my code:

var title= ['Orange', 'Apple', 'Mango', 'Airplane', 'Kiwi'];
for (var i=0; i<title.length; i++){
document.write(title[i]);
}

What do I have to add?

Thanks a bunch!

like image 463
Isaac Nelson Avatar asked Jun 11 '26 10:06

Isaac Nelson


1 Answers

Start by learning about document.getElementById and setInterval.

http://jsfiddle.net/wtNhf/

HTML:

<span id="fruit"></span>

Javascript:

var title = ['Orange', 'Apple', 'Mango', 'Airplane', 'Kiwi'];

var i = 0;  // the index of the current item to show

setInterval(function() {            // setInterval makes it run repeatedly
    document
        .getElementById('fruit')
        .innerHTML = title[i++];    // get the item and increment i to move to the next
    if (i == title.length) i = 0;   // reset to first element if you've reached the end
}, 1000);                           // 1000 milliseconds == 1 second
like image 111
Trevor Dixon Avatar answered Jun 12 '26 22:06

Trevor Dixon



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!