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()";
Share:
58,382

Related videos on Youtube

nidhi
Author by

nidhi

Updated on February 26, 2021

Comments

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

    • Dzung Nguyen
      Dzung Nguyen over 11 years
      tried using jQuery, your life will be much easier :D
  • nidhi
    nidhi over 11 years
    i need to pass parameter also..how can i?
  • mike
    mike over 11 years
    in this case you have to replace CalCal inside addEventListener and attachEvent with an anonymous function like this: function() { CalCal(yourParameter); }
  • fiacobelli
    fiacobelli over 10 years
    element1.onclick=function(){CalCal();} should be the correct syntax here.
  • IProblemFactory
    IProblemFactory over 10 years
    Nope, CalCal is just an function reference, u would do also function reference creating anonymous function(){}.
  • Roxy'Pro
    Roxy'Pro almost 5 years
    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?