31

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?

1
  • tried using jQuery, your life will be much easier :D Commented Nov 5, 2012 at 9:34

3 Answers 3

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i need to pass parameter also..how can i?
in this case you have to replace CalCal inside addEventListener and attachEvent with an anonymous function like this: function() { CalCal(yourParameter); }
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

1 Comment

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?
3

Try

element1.onclick=CalCal;

instead:

element1.onclick="javascript:CalCal()";

2 Comments

element1.onclick=function(){CalCal();} should be the correct syntax here.
Nope, CalCal is just an function reference, u would do also function reference creating anonymous function(){}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.