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

200
Views
Why my function i event listener can't be called again after initial calling?

I have the following code:

HTML

 <button>Add Name</button>
 <ul id="names"></ul>

JS

class NameField {
    constructor(name) {
        const field = document.createElement('li');
        field.textContent = name;
        const nameListHook = document.querySelector('#names');
        nameListHook.appendChild(field);
    }
}

class NameGenerator {
    constructor() {
        const btn = document.querySelector('button');
        btn.addEventListener('click', this.addName);
    }

    addName() {
        const name = new NameField("Max");
    }
}

const gen = new NameGenerator();

so here when i click on the button, then every time the function addName gets executed and max is printed in the HTML.

But when i change the line to:

 btn.addEventListener('click', this.addName());

then i get initially printed Max on the browser HTML which is expected because i call the function immediately, i did not ommited the ().

But i don't understand why after the iniitial printing,when i click on the button i don't get printed Max again ? why is that ?

Okay i got initial printing on HTML, but should not i get printed now again Max when i click on the button ? And why am i not getting ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is because you have to hand over a reference to a function.
If you write

 btn.addEventListener('click', this.addName());

javascript calls this.addName() instantly and executes the return value of this.addName() when you click the button.

But this.addName() has no explicit return value, so it returns the standard Javascript return value, which is undefined.

So essentially what your code does is

btn.addEventListener('click', undefined);

except that this undefined is returned from your call to this.addName() (which runs the function once, hence you see the console output).

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!