How to add onclick to a html element dynamically using javascript

user3454558 picture user3454558 · Mar 24, 2014 · Viewed 58.5k times · Source

I am able to create a button element and add an onclick event as shown below.

elem.onclick=function()
{
alert("qweqweqwe");
}        

How do I go about using a predefined function instead of defining a function inside of the event? Something like:

elem.onclick=func();

Answer

ylerjen picture ylerjen · Mar 24, 2014

add an eventlistener to the element which has a defined function to call :

elem.addEventListener("click", func, false); //where func is your function name

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener