Yassir Yassir - 7 months ago 10
Javascript Question

Javascript / JQuery: browse through an array and put elements inside a div

so I made a function that changes the text inside a certain div by elements from an array, this function browses an array of strings, then when it reaches its end, it starts from the beginning

here is the JQuery code:

$(document).ready(function() {

//This is the array with multiple elements
var array1=["word1" , "word2" , "word3" , "word4" , "word5" , "word6" ];
var i=0;

//This is my function
function f1()
{
if(i<6)
{
$('#change').fadeOut('slow', function() {
$(this).text(array1[i]).fadeIn('slow');
});
i++;
}
else
{
i=0;
$('#change').fadeOut('slow', function() {
$(this).text(array1[i]).fadeIn('slow');
});
i++;
}

}

$("#btn1").click(f1);
});


This is the element that should change on each click

<h3 id="change">this is a text</h3>


And of course there is the button

<button id="btn1">click</button>


Now my problem is that, the function shows the elements like this:

word2 --> word3 --> word4 --> word5 --> word6 --> word6 -->word2

It doesn't show the first element, instead it shows the 6th element twice, can you tell me what's wrong with it?

Answer

The fadeOut function is asynchronous, so your i++ happens before the function actually is completed. What you need to do is move your i++ to after the animation has finished.

See here:

if(i<6)
{
    $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        i++; // <-- move here
    });
}
else
{
    i=0;
    $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        i++; // <-- move here
    });
}
Comments