Issue
I've created a program where the user uploads a .txt file. Now I want to create a button where I click on it and the it shows the content of the .txt file **line by line with a little delay between **
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
document.getElementById('output')
.textContent = fr.result;
}
fr.readAsText(this.files[0]);
})
<input type="file" name="inputfile" id="inputfile">
<br>
<pre id="output"></pre>
Solution
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
if (!fr.result) { // if empty result do not execute below code
return;
}
const resultAsArray = fr.result.split('\r\n'); // split the text into array by new line (\r\n)
let index = 0; // Take the first line
const displayInterval = setInterval(() => { // create an interval that executes every 1 second
if (index === (resultAsArray.length - 1)) { // check if the current index is equal to last item index
clearInterval(displayInterval); // if true, exit the interval
return;
}
let html$ = document.getElementById('output').innerHTML; // capture previous html
html$ += '<div>' + resultAsArray[index] + '</div>'; // append new line data to previous html
document.getElementById('output').innerHTML = html$; // display the data into output element
index++; // increment for the next line
}, 1000);
}
fr.readAsText(this.files[0]);
})
<input type="file" name="inputfile"
id="inputfile">
<br>
<div id="output"></div>
Test text.txt file content
lorem
ipsum
generator
Answered By - Alaksandar Jesus Gene
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.