With jQuery you’ll have event delegation out of the box, but if you are using Prototype or MooTools you are less fortunate – that’s until now!
I have implemented a generic event delegation JavaScript library. It works for change, submit, focus and blur events – along with all bubbling events.
I’m successfully using the library in a large Web Application with over 6,000 lines of JavaScript code (and 60,000 lines of Java code). Some screens are displaying huge amounts of data (over 20,000 INPUTs).
It’s used like this:
<html> <head> <title>Event Delegation with Prototype</title> <script type="text/javascript" src='prototype.js'></script> <script type="text/javascript" src='delegate-generic.js'></script> <script type="text/javascript" src='delegate-prototype.js'></script> <script type="text/javascript"> document.observe('dom:loaded', function() { $('someDIV').delegate('submit', '.dont-submit', function(e) { e.stop(); alert('The form was not submitted!'); }); }); </script> </head> <body> <div id="someDIV"> <form class="dont-submit"> <input type="submit" value="Submit"> </form> <form class="dont-submit"> <input type="submit" value="Submit"> </form> </div> </body> </html>
Try it out!