Array jackery fade-in elements

Good morning. I am having a problem using Javascript to process data inside a function. I am new to Javascript, so hopefully there is a simple explanation.

My goal is to sequentially display each element from the array, fade each of them and exit it. This process will be started after calling the function by pressing 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 the array. However, it performs the display of the desired number of times, fading and calling this last value.

Here is the code I wrote:

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);
    }
});

CodePen http://codepen.io/cg893/pen/rLgLAP

, Javascript , , . , fade-in/fade-out , .

(, example2), fade-in/fade-out html. - , . - html, - , ? .

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>
Hide result
+4
1

for-loop displayText(). , displayText() .

$button.on('click', function(){

  function Loop () {           
    setTimeout(function () {    
    displayText(i);           
  i++;                    
  if (i < 10) {            
     Loop();           
    }                       
   }, 2600)
  }
  Loop();

  });
+1

Source: https://habr.com/ru/post/1652068/


All Articles