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

289
Visualizações
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 Respostas
Responde à pergunta

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