How to add click event to an element?

If you don’t have an id and don’t have any selector library and you want it to work in older browsers, then it takes a bit more work. If you can put an id on it, it’s quite simple. If not, it takes more code:

var links = document.getElementsByClassName("MyClass");
links[0].onclick = function() {
    // put your click handling code here
    // return(false) if you don't want default click behavior for the link
}

Since getElementsByClassName is not universally available in older browsers, you would need a shim to implement it when not present. Or, you could get all the links in your document with:

var links = document.getElementsByTagName("a");

and then cycle through that list until you find the one you want (perhaps checking the class name).

If you can put an ID on the link:

<a href="http://braza.com/share" id="specialLink" class="MyClass" >Yummy</a>

Then, it just takes this code:

document.getElementById("specialLink").onclick = function() {
    // add code here
}

If you’re going to do this regularly, the adding an event listener is a little more extensible than using the onclick property, but if you don’t have any framework, then you need a function for adding an event listener that handles older versions of IE.

Leave a Comment

tech