Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert items from an array into a div when clicking

I have an array with predefined lines:

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

I have a div, which i created with JS and styled it with my CSS:

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

Right now i have that code that can animate the texts fadeIns and fadeOuts on click:

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

But it is not a cycle that can iterate through my array items, it will be showing the predefined text all the time.

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

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

That cycle is not working, i don't have any console errors, but the logic here is flawed. Can somebody help me?

like image 896
Maxim Korotkov Avatar asked Oct 17 '22 06:10

Maxim Korotkov


1 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>
like image 145
Niklesh Raut Avatar answered Oct 27 '22 01:10

Niklesh Raut