Handling “onclick” event with pure JavaScript

All browsers support this (see example here):

mySelectedElement.onclick = function(e){
    //your handler here
}

However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener (needs shim for IE8-)

mySelectedElement.addEventListener("click",function(e){
   //your handler here
},false);

Here is a working example:

var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
    button.disabled = "true";
},false);

And html:

<button id='myButton'>Hello</button>

(fiddle)

Here are some useful resources:

  • addEventListener on mdn
  • The click event in the DOM specification
  • Click example in the MDN JavaScript tutorial

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)