65.9K
CodeProject is changing. Read more.
Home

JavaScript AddEventByAttributeValue

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Jan 7, 2011

CPOL
viewsIcon

8527

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

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:

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:

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.

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.