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

288
Views
Is it possible to pass parameters to a function reference in JavaScript

I have some code where I'm passing a function as an event. I want to call the function when a button is clicked but the function requires a parameter. I can pass the parameter by writing btn.addEventListener('click', displayMessage('Test'); but the function is invoked immediately. I only want to call the function when the button is clicked. Is it possible to pass the parameter without immediately invoking the function?

function displayMessage(messageText) {
        const html = document.querySelector('html');

        const panel = document.createElement('div');
        panel.setAttribute('class','msgBox');
        html.appendChild(panel);

        const msg = document.createElement('p');
        msg.textContent = messageText;
        panel.appendChild(msg);

        const closeBtn = document.createElement('button');
        closeBtn.textContent = 'x';
        panel.appendChild(closeBtn);

        closeBtn.addEventListener('click', () => panel.parentNode.removeChild(panel));
}

const btn = document.querySelector('button');
/* To avoid calling the function immediately, I do not use the function invocation
 * operator. This prevents me from passing parameters, however.
 */
btn.addEventListener('click', displayMessage); 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Run it as a callback.

btn.addEventListener('click', () => displayMessage('text')); 

That way it will be executed only when the click event runs.

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!