Skip to content Skip to sidebar Skip to footer

Add Onclick Event Programmatically

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 anoth

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

Post a Comment for "Add Onclick Event Programmatically"