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();
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
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;");
1)
function myfunction(){
alert("hello");
}
elem.onclick=myfunction();
or
2)
var myfunction=function(){
alert("hello");
}
elem.onclick=myfunction;
//or
elem.onclick=myfunction.call();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With