Add onclick event programmatically
58,382
Solution 1
But keep in mind that addEventListener
is supported in IE just from version 9. To support older versions of IE you could use something like that:
if (element1.addEventListener) { // all browsers except IE before version 9
element1.addEventListener("click", CalCal, false);
} else {
if (element1.attachEvent) { // IE before version 9
element1.attachEvent("click", CalCal);
}
}
Solution 2
Yes you can add an onclick event programmatically in javascript like this:
element1 = document.getElementById("your_tag_id");
element1.addEventListener("click", CalCal)
This attaches an onClick event to tags with id="your_tag_id".
You can also remove the onclick event like this:
element1.removeAttribute("click");
More at https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
Solution 3
Try
element1.onclick=CalCal;
instead:
element1.onclick="javascript:CalCal()";
Related videos on Youtube
Author by
nidhi
Updated on February 26, 2021Comments
-
nidhi about 3 years
How do I add an
onclick
event to a tag in HTML programmatically?I want to be able to click a link, and have an
onclick
event attached to a Javascript function take effect on another tag.Here is what I have so far:
var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); var element1 = document.createElement("input"); element1.type = "text"; element1.id="List["+num+"].id"; element1.name="List["+num+"].id"; element1.onclick="javascript:CalCal()"; cell1.appendChild(element1);
I want to call a Javascript function
CalCal()
ononClick
event. Is this possible?-
Dzung Nguyen over 11 yearstried using
jQuery
, your life will be much easier :D
-
-
nidhi over 11 yearsi need to pass parameter also..how can i?
-
mike over 11 yearsin this case you have to replace
CalCal
insideaddEventListener
andattachEvent
with an anonymous function like this:function() { CalCal(yourParameter); }
-
fiacobelli over 10 yearselement1.onclick=function(){CalCal();} should be the correct syntax here.
-
IProblemFactory over 10 yearsNope,
CalCal
is just an function reference, u would do also function reference creating anonymousfunction(){}
. -
Roxy'Pro almost 5 yearswhat is proper way of adding events to an HTML elements, programtically using javascript or directly on HTML element? I guess addEventListener() is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other on same element?