JavaScript Click Events on Tables

Sometimes it becomes necessary to obtain click events on very large sets of data. For example, my usage involved a very large table, which you could click and edit any cell. This table could potentially be 43 columns and a 1000 rows at most. That is a LOT of javascript events to register. In fact, I don’t think you’d have much luck at all performance wise even if you tried to do that. However, there is an easy solution to this situation.

First lets assume you have table on an HTML page something like this:


Obviously this is a small table, but works fine for this example. Instead of attaching an onclick=”eventname” to each “td” element, we can simply add a single event to the whole number to manage it. Check out this script:


So you’ll notice the first step is to attach a click event handler to the entire table. Then whenever the table is clicked, we do a check to ensure it was a “TD” element thats has been clicked (or whatever element you may want). Then you can extrapolate your source element exactly the same as if the event was called on that element. In this example I just output the contents of the cell, but lets you see how you can implement this so easily, and how this method would save a ton on performance and scalability is not an issue!!!

Much much cleaner as well, rather than attaching events to each TD or writing the events on the markup page!