Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda