Click here to Skip to main content
15,891,902 members
Articles / Web Development / XHTML
Tip/Trick

JavaScript AddEventByAttributeValue

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
14 Jan 2011CPOL 8.4K   1   2
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)


Written By
Chief Technology Officer MammothWorkwear.com
United Kingdom United Kingdom
Senior Web Developer, Systems Architect and Entrepreneur. Technical Director of MammothWorkwear.com. More information is available at http://www.johndoherty.info/

Comments and Discussions

 
GeneralReason for my vote of 4 Nice but not live more example Pin
Hemant.rapid17-Jan-11 17:00
professionalHemant.rapid17-Jan-11 17:00 
GeneralReason for my vote of 5 Thanks for sharing! Pin
Manfred Rudolf Bihy17-Jan-11 12:10
professionalManfred Rudolf Bihy17-Jan-11 12:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.