I am writing a simple web app using Flask for the backend, and vanilla javascript in the front. The app will simply allow the user to navigate the local filesystem in the browser. It's not supposed to be a useful or good app, I'm just practicing.
My problem is that when writing the frontend js, I get to the following point, where I encounter an issue:
getData();
let root = document.getElementById('root');
async function getData() {
const response = await fetch(`http://localhost:5000/`)
const data = await response.json();
const header = document.getElementById('current')
header.textContent = '/'
for (item of data.current_directory) {
const entry = document.createElement('p');
entry.textContent = item;
const button = document.createElement('button');
button.innerHTML = 'Go'
button.addEventListener('Click', goTo(item))
root.append(entry, button);
}
}
async function goTo(location) {
const response = await fetch(`http://localhost:5000/?location=${location}`);
data = await response.json();
const header = document.getElementById('current');
header.textContent = location;
root.textContent = '';
for (item of data.current_directory) {
const entry = document.createElement('p');
entry.id = item
entry.textContent = item;
root.append(entry);
}
}
I am simply trying to fetch the directory structure,starting at root / (I'm on Linux) from the server, and then display each file/directory in the path as a <p> element, after which I create a button element that should take you to that directory when clicked.Problem is, when I open this in my browser, for some reason the eventlistener gets triggered automatically, with each loop iteration. If I check Flask's logs, I can see a whole bunch of get requests, consistent with the "goTo" function being called over and over again.
And yes I know I should probably be using a frontend framework for this, but I'd like to understand vanilla javascript before doing that.
Any suggestions?
Thanks