Attach runtime event to dynamic elements in javascript?

Viewed 22

I have created a small example on jsfiddle: https://jsfiddle.net/0rve9cwf/

In short, when I create an element dynamically and add a click handler, it is assigning the result of the called function to the new element, rather than calling the attached function during runtime, which is not the behavior I expected or wanted. Then, when you actually click the button, nothing happens. What is the best practice to attach a function to a dynamically created object which should be executed at runtime?

HTML

<html lang='en'>
    <head>
        <title>Binding event handler dynamically</title>
    </head>
    <body>
    
    </body>
</html>

JavaScript

function result(val1, val2) {
    console.log(`val1:  ${val1}, val2:  ${val2}`);
}

let btn         = document.createElement('button');
btn.textContent = 'Click me';
btn.addEventListener('click', result(
    'first value',
    'second value'
));

let body        = document.getElementsByTagName('BODY')[0];
body.append(btn);
2 Answers

All you need to do is to add a () => . You need to pass a function as a second parameter to addEventListener, and in your case your function is executed immediately.

btn.addEventListener('click', () => result(
  'first value',
  'second value'
));

i hope this solves the problem

function result(val1, val2) {
    console.log(`val1:  ${val1}, val2:  ${val2}`);
}

let btn        = document.createElement('button');
btn.textContent = 'Click me';
btn.addEventListener('click', (event) => {result(
    'first value',
  'second value'
)});

let body        = document.getElementsByTagName('BODY')[0];
body.appendChild(btn);
<html lang='en'>
    <head>
        <title>Binding event handler dynamically</title>
    </head>
    <body>
    
    </body>
</html>

Related