I have some javascript that basically loops fading in 3 different titles.
I initially had the problem where the first title ('text1') on the first loop had the 3 second delay where I wanted it to be displayed as the page loaded.
Original code: http://jsfiddle.net/7EaHF
<div style="padding:20px;"><h1 id="heroText"></h1></div>
var text = ['text1', 'text2', 'text3'];
i = 0,
$content = $('#heroText');
setInterval(function ()
{
$content.fadeOut(function ()
{
$content.text(text[i++ % text.length]).fadeIn();
});
}, 3000);
So all I did was change the order of the 'text' variable and writ the "text1" in the html so it was displayed initially on the page with no delay and then continued on with the loop in the correct order as seen here:
<div style="padding:20px;"><h1 id="heroText">text1</h1></div>
var text = ['text2', 'text3', 'text1'];
i = 0,
$content = $('#heroText');
setInterval(function ()
{
$content.fadeOut(function ()
{
$content.text(text[i++ % text.length]).fadeIn();
});
}, 3000);
My question is, can I disable the initial delay on the first 'text1' title in javascript without having to write the first 'text1' in the html? This is mainly because other people will be using and changing this code and it may get confusing if they have to always put the first to be displayed last on the variable list and update the html as well.
I guess this is quite simple but I am still learning javascript and can't find a way to do this, thanks in advance.
var text = ['text1', 'text2', 'text3'];
i = 0,
$content = $('#heroText');
// declare the function that does the work
function fadeText() {
$content.fadeOut(function () {
$content.text(text[i++ % text.length]).fadeIn();
});
}
// call it immediately so that the first text shows up
fadeText();
// set it to repeat
setInterval(fadeText, 3000);