Ezeeroc
Ezeeroc

Reputation: 178

div element not changing its text content

In a css file is some text and I want to change the text content of a div element dynamically (first showing the 1st text, then the 2nd etc.) and the problem is that even though i see that console.log(message[i].text) has the text (i.e."Insert the FIRST text you want." etc.), document.getElementById("background").innerHTML = message[i].text; is still empty.

This is the css file:

const message = [
    {
        "text":"Insert the FIRST text you want."
    },
    {
        "text":"Insert the SECOND text you want."
    },
    {
        "text":"Insert the THIRD text you want."
    },
    {
        "text":"Insert the FOURTH text you want."
    },
    {
        "text":"Insert the FIFTH text you want."
    },
    {
        "text":"Insert the SIXTH text you want."
    },
  {
        "text":"Insert the SEVENTH text you want."
    },
  {
        "text":"Insert the EIGHTH text you want w this is just to test the words w ww www."
    }
]

This is the js function:

function insertText(a, b){
  (function theLoop (i) {
    setTimeout(function () {
      document.getElementById("background").innerHTML = message[i].text;
      if (i++ < b-1) {    
        theLoop(i);       
      }
      else {
        i = a;
        //theLoop(i);
      }
    }, delayValue);
  })(a, b);
}

And this is how Im calling it:

var l = message.length; 
insertText(0, l);

Im sure it is something easy, but I cant figure it out. Thanks a lot.

Upvotes: 0

Views: 337

Answers (1)

Mamun
Mamun

Reputation: 68933

Since you didn't provide details of the question like the HTML, the error you are getting (if any), it is really difficult to answer the question.

Though I was able to get going with your code by adding one HTML element and setting the value for delayValue in setTimeout().

Try the following:

const message = [
    {
      "text":"Insert the FIRST text you want."
    },
    {
      "text":"Insert the SECOND text you want."
    },
    {
      "text":"Insert the THIRD text you want."
    },
    {
      "text":"Insert the FOURTH text you want."
    },
    {
      "text":"Insert the FIFTH text you want."
    },
    {
      "text":"Insert the SIXTH text you want."
    },
    {
      "text":"Insert the SEVENTH text you want."
    },
    {
      "text":"Insert the EIGHTH text you want w this is just to test the words w ww www."
    }
]


function insertText(a, b){
  (function theLoop (i) {
    var delayValue = 1000;
    setTimeout(function () {
      document.getElementById("background").innerHTML = message[i].text;
      if (i++ < b-1) {    
        theLoop(i);       
      }
      else {
        i = a;
        //theLoop(i);
      }
    }, delayValue);
  })(a, b);
} 
var l = message.length; 
insertText(0, l);
<div id="background"></div>

Upvotes: 2

Related Questions