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

299
Visualizações
Why function calling using onclick only works when nested in another function in JavaScript?

Why do functions nested in an anonymous function wait for button click (as it should), but when the function is not nested it runs on page load without waiting for button click?

Working example:

btn1.onclick = function() {cityChoice(1)};
     //code works only on button click as expected

Not working example:

btn1.onclick = cityChoice(1);
     //function runs on pageload without waiting for button click?

Any links to documentation/articles are welcome, as I could not find them on Google nor on StackOverflow that explained this.

Coding language: JavaScript (vanilla)
Skill level: Beginner
Editor: Visual Studio Code
OS: Windows 7

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

btn1.onclick = cityChoice(1); isn't a nested function. You merely called the cityChoice function and its return value saved as onclick property of variable btn1.

There are several ways you can achieve the same thing to bind listener to an event:

btn1.onclick = function() { } <-- anonymous function

btn1.onclick = () => { } <-- arrow function


In conclusion:

btn1.onclick = cityChoice(1) <-- cityChoice function is invoked and its value is saved to btn1.onclick

Ref:

Anonymous functions in JS

Arrow functions in JS

about 4 years ago · Juan Pablo Isaza Relatório

0

cityChoice is a function and I assume you're trying to pass it your default argument 1 the problem you're seeing is that you're invoking cityChoice in your second example and assigning the result of cityChoice(1) to onclick instead of registering an event handler. This I assume would return a normal javascript object. onclick needs to be an event handler (any function anonymous or not)

about 4 years ago · Juan Pablo Isaza Relatório

0

When you use this cityChoice(1); without nested function.

Javascript understand it like you type it without onclick event It's like you call it on page load.

But function statment assign new function when called it call cityChoice(1).

about 4 years ago · Juan Pablo Isaza Relatório
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