JavaScript AddEventListener method

Posted on April 25th, 2009 at 5:38 pm

Despite it’s already outdated a lot of programmers are still using onClick, onChange and so … events in the tags attributes and i actually find myself doing it sometimes as well. So i want to show you nice and clean way of adding events to the objects/tags without implicitly declaring some action in the tag – sounds complicated but it’s really not.

One problem with the addEventListener method is that, javascript file is usually loaded in the header while, while HTML is not yet loaded. So when we try to add events to document objects we will get errors that we are trying to assign “something” to not existing object (or something similar). Therefore first we need a script that will register all the vents once HTML page is loaded.

function addLoadEvent(func)
{
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

I am not as smart as i present myself here, the truth is that i took this code from one of the articles at SitePoint.com, however i do not remember which, if you know which one is it, post it in the comments i will add a reference.

Ok, basically what this function does is, it fires function “func” passed as an argument to the addLoadEvent once a page is loaded. If we add function registerEvents in to the script then we will use addLoadEvent like this:

function registerEvents()
{
}
 
addLoadEvent("registerEvents");

Now we can go to the topic of this article: addEventListener. Like i said events are assigned to the tags (or objects in terms of DOMDocument). So lets’ assume that somewhere in the HTML code we have something like this.

...
<a id="link_to_example" href="http://example.com">external link</a>
...

To change default anchor behavior we need to overwrite it’s “onclick” method, with addEventListener it’s done like this. Note remember to add this code inside of registerEvents function.

document.getElementById("link_to_example").addEventListener(
    "click",
    function() {
        alert("Please do not leave");
        return false;
    },
    false
);

Now when you click that link the popup message will apper. Using this method you can easily add events to any object in your document. Of course instead of writing anonymous function for each event you write function name and that function will be executed when needed.

That was just a quick example for further reference visit:

About this author

Greg Winiarski

Greg Winiarski is a freelance PHP and JavaScript programmer. He specializes in web applications and WordPress development.

3 Responses to “JavaScript AddEventListener method”

  1. NIck says:

    A final downloadable example would be appreciated!

  2. Jurgen says:

    Wouldn’t it be a lot nicer to do something like this for initialization?


    if(window.addEventListener)
    window.addEventListener('load', registerEvents, false);
    else if(window.attachEvent)
    window.attachEvent('onload', registerEvents);

    It seems a bit strange to do an article on eventlisteners and then not using them where they apply most. What you did is exactly what you wanted to avoid in HTML but you did the same on the javascript level.

    So i want to show you nice and clean way of adding events to the objects/tags without implicitly declaring some action in the tag

    You also don’t have the problem of saving the old onload-handler.

  3. eHlrJX Bravo! Nice Article.,

Leave a Reply