How do you catch a click event with plain Javascript?

document.getElementById('element').onclick = function(e){
  alert('click');
}

DEMO: http://jsfiddle.net/e9jZW/1/


By adding an event listener or setting the onclick handler of an element:

var el = document.getElementById("myelement");

el.addEventListener('click', function() {
  alert("Clicked");
});

// ... or ...

el.onclick = function() {
  alert("Clicked");
}

Note that the even listener style allows multiple listeners to be added whereas the callback handler style is exclusive (there can be only one).

If you need to add these handlers to multiple elements then you must acquire them as appropriate and add them to each one separately.


I usaly create a kind of global event handler, very powerful, you can capture className, of the event "types" nodeTypes, you name it, i hope people will find this useul

document.onclick = eventRef

function eventRef(evt) {
    var han;
    evt || (evt = window.event);

    if (evt) {
        var elem = evt.target ? han = evt.target : evt.srcElement && (han = evt.srcElement);

         // evt.type could be, mouseup, mousedown...
        // elem.id is the id or the element
        // elem.className is the class name of the element
        // you could nest expression, use substrings to extract part of a className
        if (evt.type=="click" && elem.id == "gotit" || elem.className == "someClassName") {  
            alert(elem.id);
        }
    }
}