Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add onclick to a html element dynamically using javascript

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();
like image 622
user3454558 Avatar asked Mar 24 '14 08:03

user3454558


3 Answers

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

like image 191
ylerjen Avatar answered Nov 11 '22 02:11

ylerjen


The best way which i found out for myself is like below.

const li = document.createElement('li');
        li.innerText = "client";
        li.id ="key";
        li.className = "client-class";
        li.setAttribute("onclick","valid;");
like image 44
Achuth hadnoor Avatar answered Nov 11 '22 02:11

Achuth hadnoor


1)

function myfunction(){
alert("hello");
}

elem.onclick=myfunction();

or

2)

var myfunction=function(){
alert("hello");
}
elem.onclick=myfunction;
//or
elem.onclick=myfunction.call();
like image 23
Tuhin Avatar answered Nov 11 '22 04:11

Tuhin