I'm trying to create a piece of js that will cycle through displaying classes, and then loop back to the start. for a better example of what I mean;
I have a sentence, example:
'I like cats.'
I would like the word 'cats' to be substituted with the words 'dogs', 'hamsters', 'lions' and 'fish' for example. every 2 seconds, one word will be changed for another with a fade, and once the last one is reached, the cycle will begin again.
I am currently trying to do this by having all 5 words with a different class, and trying to change the display of each class every 2 seconds. However, I am new to js, and I realise, that this is inelegant, and possibly incorrect.
thanks in advance for any help guys :)
One way is to change it every 2 seconds with setInterval functionality of javascript. You have an array with the animals and you loop through it using counter. Every time the counter reaches the length of the array minus 1 it will be reset. You can stop the loop be clearing the setInterval. It's done with clearInterval(variable) and you pass in the setInterval variable - animalsLoop in our case.
The code:
HTML:
<div class="js-animals"></div>
Javascript:
var animals = ['cats', 'dogs', 'lions', 'fish'];
var counter = 0;
var animalsLoop = setInterval(function() {
$('.js-animals').text(animals[counter]);
if (counter === animals.length - 1) {
counter = 0;
} else {
counter++;
}
}, 2000);
JSFiddle: http://jsfiddle.net/x7wr4zLq/4/
EDIT: If you want a nice fade out / fade in transition we forget about the setInterval. What we'll be using is going to be jQuery fadeIn() and fadeOut() with a loop function. So what happens is that we call the loop[ function once the fadeOut is triggered and after it finishes the we check if we need to reset the counter and we trigger the fadeIn. When fadeIn is finished we call the loop function again and so on and so on ...
The delay() is used to dalay the fadeOut. You can set it to how much time do you want the text to be displayed before it goes away.
The code:
HTML:
<div class="js-animals"></div>
Javascript:
var animals = ['cats', 'dogs', 'lions', 'fish'];
var counter = 0;
// Initialize the first animal
// so that we don't wait for the first iteration
$('.js-animals').text(animals[counter]);
function loop() {
$('.js-animals').delay(500).fadeOut(500, function() {
// Check if we need to reset the counter
if (counter === animals.length - 1) {
counter = 0;
} else {
counter++;
}
$(this)
.text(animals[counter])
.fadeIn(500, loop);
});
}
loop();
JSFiddle: http://jsfiddle.net/x7wr4zLq/3/