0

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?

yusuf
  • 3,591
  • 8
  • 45
  • 86
  • 1
    Does this answer your question? [How to read a local text file?](https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file) – mo3n Jan 18 '22 at 08:32
  • No, it does not. I did some edit on the question. Could you take a look? Thanks! – yusuf Jan 18 '22 at 08:33

1 Answers1

1

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.

Sadra Saderi
  • 52
  • 1
  • 8