Add your custom method on every link without modifying existing code through JavaScript

Posted on November 23, 2009. Filed under: Java Script, Technical | Tags: , |

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 )

Recently on Ajit Kumar Pal's Blog...

Google Latitude History and Alerts

Posted on November 11, 2009. Filed under: Computer, Google | Tags: , , , , |

Some innovative Computer mouse

Posted on November 6, 2009. Filed under: Computer | Tags: , |

ajit invites you to join TheCityGuide.in

Posted on November 5, 2009. Filed under: Technical |

Spice up your mobile

Posted on November 4, 2009. Filed under: Technical |

Optimizing JavaScript code

Posted on November 3, 2009. Filed under: Java Script, Technical | Tags: , , |

Lol Dogs – just doggy style

Posted on October 28, 2009. Filed under: Fun, Fun Stuff | Tags: , , , , |

More Look-A-Like

Posted on October 28, 2009. Filed under: Fun, Look-A-Like | Tags: , , |

Some More Fail Photos

Posted on October 28, 2009. Filed under: Fun, Fun Stuff, fail photos | Tags: , , |

NEED OF ASP.NET ASHX Handler

Posted on October 22, 2009. Filed under: C#, Custom Handlers | Tags: |

Using ASHX files to retrieve DB images

Posted on October 21, 2009. Filed under: C#, Technical | Tags: , |

Liked it here?
Why not try sites on the blogroll...