yusuf
yusuf

Reputation: 3781

reading and displaying a text from a file line by line using javascript on html page

I am just learning javascript, so I need your help. I have a text file, like following;

Text1
Text2
Text3
.....
.....
Textn

I would like to read all the content from the file line by line, so text by text, and display on html page one by one. One text will blink, disappear, and then next text will blink, disappear, etc. When it comes to the end, then it will start from the beginning of the file, and continue again line by line.

How can I do it?

Upvotes: 0

Views: 132

Answers (1)

Sadra Saderi
Sadra Saderi

Reputation: 385

You can do it this way:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example</title>
</head>

<body>
  <h1 id="my-element">Value</h1>

  <script>
    var target = document.getElementById("my-element");

    var content = null;
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "content.txt");
    xhr.onload = () => {
      content = xhr.response.split(/\r?\n/);
      let counter = 0;
      setInterval(() => {
        target.innerHTML = content[counter++ % content.length];
        setTimeout(() => target.innerHTML = "", 500);
      }, 1000);
    };
    xhr.send();

  </script>
</body>

</html>

But note that it doesn't work using file protocol and you should run a local server to use it.

Upvotes: 1

Related Questions