0

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); 
Chad
  • 11
  • 1
  • 2
  • [`Function.prototype.bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) – phuzi Jan 05 '22 at 12:52
  • Side note: You should be inserting content in `document.body` not in root `` – charlietfl Jan 05 '22 at 12:55

1 Answers1

1

Run it as a callback.

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

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

Esszed
  • 597
  • 1
  • 3
  • 15