Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / XHTML

JavaScript AddEventByAttributeValue

4.50/5 (2 votes)
14 Jan 2011CPOL 8.5K  
Add a JavaScript event handler to any XHTML element where the tagName and attribute value match criteria.

Introduction


I have used this function countless times over the years. It was designed to be a fast/lightweight/cross browser way to assign functions to the events of any element on the page matching a specific criteria. It also works with expando attributes (custom attributes assigned at runtime).


The Function


JavaScript
function AddEventByAttributeValue(t/*tagName*/, p/*propery*/, v/*value*/, e/*event*/, f/*function*/)
{
    var n = document.getElementsByTagName(t);
    for (var i=0, l=n.length; i<l; i++)
    {
        if (n[i][p] == v) { n[i][e] = f; }
    }
}

Using the Code


You can use the code in the following way:


JavaScript
AddEventByAttributeValue("a", "className", "lightbox", "onclick", function (e) {
    e = e || event;
    if (this.href.lastIndexOf(".jpg") == this.href.length - 4) {
        alert("this is an image link");
    }
    e.cancelBubble = true;
    e.returnValue = false;
    return false;
});

or alternatively:


JavaScript
function lightboxImageClick(e) 
{
    e = e || event;
    if (this.href.lastIndexOf(".jpg") == this.href.length - 4) {
        alert("this is an image link");
    }
    e.cancelBubble = true;
    e.returnValue = false;
    return false;
}
AddEventByAttributeValue("a", "className", "lightbox", "onclick", lightboxImageClick);

to affect all element types where an attribute exists and value equals, use an astrix * as the tagName.


JavaScript
AddEventByAttributeValue("*", "className", "lightbox", "onclick", lightboxImageClick);

Points of Interest


This function is aimed at projects that do not require bloated JavaScript frameworks. It does not provide a method to remove events, although this could be added if required.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)