I have an array and all I want to do is when the page is fully loaded a word (inside a span tag in the html) fade out with jQuery and replaced with a word from the array, show the new word for 2 seconds and be replaced again by the next word of the array until the array is over.
It’s so simply but I’ve tried a thousand different ways with loops and always go over the array before displaying anything on the website and when it is fully loaded shows me the last word of the array.
Here is one of my attemps:
$(function(){
var words=new Array('red','blue','yellow','black','white','orange',
'green','brown');
var wordList;
for(var i in words){
wordList=words[i];
$("#word").fadeOut(200).html(wordList).fadeIn(200).delay(2000);
}
});
Probably the mistake is very silly but I’m starting with javascript and I’m going crazy… Thanks
[]instead ofnew Array()..htmlis not an animation function and will run immediately (ignoring.delay), so it won’t go word by word. Set it only when the animation completes with the second argument you can pass to animation functions.setTimeoutto run a function after a certain amount of time. The problem you’ll encounter is scoping with aforloop (wordListwill be the same each time). However, you can make use of$.eachand pass a function (a function will introduce a new scope, and the scoping problem will go away).http://jsfiddle.net/pimvdb/EkaAF/