JavaScript: Adding an onClick handler without overwriting the existing one

javascript, jquery, onclick

Solution

You need to create a closure to preserve the original `onclick` value of each link:

<a href="#" onclick="alert('hi');return false;">Hi</a>
<a href="#" onclick="alert('there');return true;">There</a>
<script type="text/javascript">
function adaptLinks() {
    var links = document.getElementsByTagName('a');
    for (i = 0; i != links.length; i++) {
        links[i].onclick = (function () {
            var origOnClick = links[i].onclick;
            return function (e) {
                if (origOnClick != null && !origOnClick()) {
                    return false;
                }
                // do new onclick handling only if
                // original onclick returns true
                alert('some work');
                return true;
            }
        })();
    }
}
adaptLinks();
</script>

Note that this implementation only performs the new onclick handling if the original onclick handler returns true. That's fine if that's what you want, but keep in mind you'll have to modify the code slightly if you want to perform the new onclick handling even if the original handler returns false.

More on closures at the comp.lang.javascript FAQ and from Douglas Crockford.

Problem

I'm trying to modify all links on a page so they perform some additional work when they are clicked. A trivial approach might be something like this: ``` function adaptLinks() { var links = document.getElementsByTagName('a'); for(i = 0; i != links.length; i++) { links[i].onclick = function (e) { <do some work> return true; } } } ``` But some of the links already have an onClick handler that should be preserved. I tried the following: ``` function adaptLinks() { var links = document.getElementsByTagName('a'); for(i = 0; i != links.length; i++) { var oldOnClick = links[i].onclick; links[i].onclick = function (e) { if(oldOnClick != null && !oldOnClick()) { return false; } <do some work> return true; } } } ``` But this doesn't work because oldOnClick is only evaluated when the handler is called (it contains the value of the last link as this point).

Original source