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).
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.
Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions. Thank you!
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.
Use the off() method to override jQuery event handlers. This method is used to remove an event handler.
Don't assign to an event handler directly: use the subscribe model addEventListener / attachEvent instead (which also have remove pairs!).
Good introduction here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With