Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Javascript "onclick" eventlistener triggered automatically, without getting the specified input

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!