Good morning. I have run into a problem with my use of Javascript to process data within a function. I am new to Javascript so hopefully there is a simple explanation.
My goal is to display each item from an array sequentially, fading each in and out. This process will be started after calling the function by clicking the button on the screen.
I tried to do this by iterating through the members of the array by index number. Instead of processing and displaying each element by index number the function iterates through the entire sequence, but displays only the last element of array. However it does perform the display the desired number of times by fading in and out on this last value.
Here is the code I have written;
var tarList = [ "Sentence one.",
"Sentence two.",
"Sentence three.",
"Sentence four.",
"Sentence five.",
"Sentence six."];
var $button = $('button');
var index = 0;
function displayText(indexNo) {
$("h3").text(
tarList[indexNo]).fadeIn(700).delay(1200).fadeOut(700);
}
$button.on('click', function(){
for (var i=0; i < tarList.length; i++) {
console.log(i);
displayText(i);
}
});
The full effort on CodePen http://codepen.io/cg893/pen/rLgLAP
I don't understand why Javascript iterates through the full range and only calls the display function with the last value in spite of the fact that the call to the display function is inside the scope of the iteration. I also do not understand why the fade-in/fade-out command executes the correct number of times but only uses the last item from the array.
I have seen other examples (example, example2 ) where the fade-in/fade-out sequence is performed on list elements from the html. My goal is to use the array as a separate data source so that the values can be processed as a group. If the only way to do this is by including the values in the html can someone offer suggestions on how best to do this? Thank you.
var tarList = [ "Sentence one.",
"Sentence two.",
"Sentence three.",
"Sentence four.",
"Sentence five.",
"Sentence six."];
var $button = $('button');
var index = 0;
function displayText(indexNo) {
$("h3").text(
tarList[indexNo]).fadeIn(700).delay(1200).fadeOut(700);
}
$button.on('click', function(){
for (var i=0; i < tarList.length; i++) {
console.log(i);
displayText(i);
}
});
#button_1 {
left: 50%;
top: 50%;
position: absolute;
}
h3 {
position: relative;
margin-top: 1em;
text-align: center;
font-size: 2em;
font-family: Arial;
transition: color 1s ease-in-out;
}
<script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script>
<h3 id="target_text">Start</h3>
<button id="button_1" type="submit" >Go!</button>