Reputation: 1762
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?
Upvotes: 1
Views: 64
Reputation: 42044
Another solution can be based on the data attributes. The completion of the management of the entire operation is very important in order to avoid to start another cycle before the current one finishes:
//This is the array with multiple elements
var array1=["word1" , "word2" , "word3" , "word4" , "word5" , "word6" ];
$(function () {
$("#btn1").on('click', function(e) {
// disable button till the operation is completed
$(this).prop('disabled', 'disabled');
// use data-currentIndex to store the local variable i
var idx = $('#change').data('currentIndex');
if (idx === undefined) {
idx = 0;
}
$('#change').fadeOut('slow', function() {
$(this).text(array1[idx]).fadeIn('slow');
idx = (idx <= (array1.length - 2)) ? (idx + 1) : 0;
$('#change').data('currentIndex', idx);
// enable button because the operation is now completed
$("#btn1").removeProp('disabled');
});
});
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<h3 id="change">this is a text</h3>
<button id="btn1">click</button>
Upvotes: 1
Reputation: 1235
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
});
}
Upvotes: 2