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

298
Views
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 answers
Answer question

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 Report

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 Report

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 Report
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!