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