Insert elements from array into div when clicked

I have an array with predefined strings:

var linesArr = ["asd", "dsa", "das"]; 

I have a div that I created using JS and styled it using my CSS:

  var div = document.createElement("div"); div.className = "storyArea"; div.innerHTML = linesArr[0]; 

Right now I have this code that can animate fadeIns and fadeOuts texts when clicked:

  $(div).click(function(){ $(this).fadeOut(1000, function() { $(this).text("Random text").fadeIn(2000); }); }); 

But this is not a loop that can go through my array elements, it will show predefined text all the time.

I tried to write a loop that can work through this, but got lost:

  $(div).click(function(){ for (var i = 1; i < linesArr.length; i++) { $(div).fadeOut(1000, function() { $(this).html(linesArr[i].fadeIn(2000)); }); }; }); 

This loop does not work, I have no console errors, but the logic here is wrong. Can someone help me?

+5
source share
3 answers

Do you want like this

 var linesArr = ["asd", "dsa", "das"]; var div = document.createElement("div"); div.className = "storyArea"; div.innerHTML = linesArr[0]; document.body.appendChild(div); $(div).click(function(){ //for (var i = 1; i < linesArr.length; i++) { $(div).fadeOut(1000, function() { index = linesArr.indexOf($(this).html()) + 1; $(this).html(linesArr[index % linesArr.length]); $("div").fadeIn(2000); }); //}; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
+2
source

In this case, you can use the show pointer to track the currently displayed item. Then, on each click, the current ones disappear and disappear in the next.

I also use the % module to return to the first element when you reach the end.

 var linesArr = ["asd", "dsa", "das"]; var show = 1; var div = document.createElement("div"); div.className = "storyArea"; div.innerHTML = linesArr[0]; $(document.body).append(div); $(div).click(function() { $(div).fadeOut(1000, function() { $(this).html(linesArr[show++ % linesArr.length]).fadeIn(2000); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
+1
source

If you need a loop, you can use a loop in IIFE:

  $('div').click(function () { (function loop(i) { $('div').html(linesArr[i]).fadeOut(1000, function () { $(this).html(linesArr[i]).fadeIn(2000); i++; if (i < linesArr.length) { loop(i); } }); })(0); }); 

 var linesArr = ["asd", "dsa", "das"]; $('div').click(function () { (function loop(i) { $('div').html(linesArr[i]).fadeOut(1000, function () { $(this).html(linesArr[i]).fadeIn(2000); i++; if (i < linesArr.length) { loop(i); } }); })(0); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Click Me</div> 

When, as a result of a full callback, your variable i has already reached the last value. To keep the scope of the variable you can use IIFE

0
source

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


All Articles