Add your custom method on every link without modifying existing code through JavaScript
I’m trying to modify all links on a page so they perform some additional work when they are clicked.
Here’s is a example shown below
<a href=”#”>Hi</a>
<a href=”#”>There</a></code>
function adaptLinks() {
var links = document.getElementsByTagName('a');
for (i = 0; i != links.length; i++) {
links[i].onclick = (function (e) {
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();
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
Read Full Post | Make a Comment ( None so far )
