Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Adding an onClick handler without overwriting the existing one

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).

like image 281
rluba Avatar asked May 21 '09 09:05

rluba


People also ask

Does addEventListener overwrite Onclick?

Note: The addEventListener() method can have multiple event handlers applied to the same element. It doesn't overwrite other event handlers. Example: Below is a JavaScript code to show that multiple events are associated with an element and there is no overwriting.

Can you have multiple onclick functions?

Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions. Thank you!

Can you have two onclick events in HTML?

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty. Save this answer.

How do you override a click event?

Use the off() method to override jQuery event handlers. This method is used to remove an event handler.


1 Answers

Don't assign to an event handler directly: use the subscribe model addEventListener / attachEvent instead (which also have remove pairs!).

Good introduction here.

like image 166
annakata Avatar answered Sep 23 '22 20:09

annakata