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:

Leave a Comment