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

85
Views
Why does js eventhandler defined in separate file run before the associated event occur

I have the following code, which works as intended

let userNameEl = document.querySelector("#username");
let startGameBtn = document.querySelector(".start-game");

startGameBtn.addEventListener("click", () => {
    if (!userNameEl.value) {
        alert("Please enter player name");
    }
}); 

But when I define the eventhandler in a separate file, the result isn't what I intended

import * as Utils from "./utils.js";

let userNameEl = document.querySelector("#username");
let startGameBtn = document.querySelector(".start-game");

startGameBtn.addEventListener("click",Utils.validatePlayerName(userNameEl));

The logic of validatePlayerName is similar to that of the anonymous function of the first addEventListener, but the result is different. It looks like Utils.validatePlayerName(userNameEl)) runs before click event is assigned.

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!