I’m trying to write a simple drag and drop html & vanilla JS to parse and process a text file. Count the number of unique words etc. This is for my benefit so everything is local.
It’s the asynchronous behaviour that has got me stumped. The code below works – simply puts the contexts of the text file to the browser window. However, it only works the second time you try this. Any ideas?
JS:
// vegetables
var theText = "";
// Setup the drop zone
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handle_drag_over);
dropZone.addEventListener('drop', handle_file_select);
function handle_drag_over(evt)
{
evt.preventDefault();
}
function handle_file_select(evt)
{
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
var output = [];
for (var i = 0; i < files.length; i++)
{
var file = files[i];
// console.log(files); // FileList {0: File, length: 1}
// console.log(files[0])// File{name: 'mytext.txt'...
// Create a new FileReader object
var reader = new FileReader();
// Set up an event handler for the load event
reader.onload = function(event)
{
// Get the resulting text from the event
theText = event.target.result;
// Do something with the file contents
console.log(theText);
};
// Read the file contents as text
reader.readAsText(file);
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
var element = document.getElementById('output');
element.innerHTML += theText;
}
function handle_drag_over(evt)
{
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
And the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Drag n' drop text</title>
<style>
body {
padding:0;
margin:0;
background:#fff;
}
p {
color:#000;
width:400px;
margin:10px auto 0;
}
#drop_zone {
border: 2px dashed rgb(0, 0, 0);
border-radius: 5px;
padding: 100px;
text-align: center;
color: rgb(187, 187, 187);
}
</style>
</head>
<body>
<p>Text file thing</p>
<p id="info"><p></p>
<div id="drop_zone">Drop TEXT file here</div>
<div id="output"></div>
<output id="list"></output>
</head>
<body>
<canvas id="canvas" width="320" height="60"></canvas>
<script src="drag_n_drop_text.js"></script>
</body>
</html>