Reputation: 21
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);
Upvotes: 0
Views: 444
Reputation: 607
Run it as a callback.
btn.addEventListener('click', () => displayMessage('text'));
That way it will be executed only when the click event runs.
Upvotes: 1