29

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() on onClick event. Is this possible?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nidhi
  • 333
  • 2
  • 9
  • 17

3 Answers3

34

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);
  }
}
mike
  • 880
  • 1
  • 8
  • 12
  • 1
    i need to pass parameter also..how can i? – nidhi Nov 05 '12 at 11:10
  • 7
    in this case you have to replace ```CalCal``` inside ```addEventListener``` and ```attachEvent``` with an anonymous function like this: ```function() { CalCal(yourParameter); }``` – mike Nov 05 '12 at 11:22
16

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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
  • what 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? – Roxy'Pro May 12 '19 at 22:00
2

Try

element1.onclick=CalCal;

instead:

element1.onclick="javascript:CalCal()";
IProblemFactory
  • 9,551
  • 8
  • 50
  • 66