views:

73

answers:

3

I was wondering if there was a way of adding javascript in every occurrence of a certain HTML tag, eg.

<td onmousedown="">

At the moment I just have it in every single one of my td tags in my table, but there must be a cleaner way. Something like adding javascript in the way CSS adds formatting.

+1  A: 

Add an event listener (See also: Quirks Mode on events and on event listeners) to your document looking for mousedown events and filter it on the basis of the originating element.

There is a good answer here on Stackoverflow as well.

Sean Vieira
Those are really useful links! I get the impression that the filtering method isn't ideal though as if you have a mouseover event then whenever you mouseover any element in the page it will check to see if it is an element that should trigger a function.
Acorn
@Acorn - I'm glad the links helped! And you are absolutely right about the filtering method, if you set the event listener on the `body`! I believe you could place the event listener on the `table` or `tbody` element, to reduce the amount of checking the browser would have to do.
Sean Vieira
+4  A: 

What your looking for is most likely "event binding." This can be done via your script rather than embedded in the HTML code. There are lots of different ways to accomplish such a task, here is one of them using "td" as in your example.

var items = document.getElementsByTagName("td");
for (var i=0; i<items.length; i++) {
  items[i].onmousedown = YourMouseDownFunction;
}
Greg W
+2  A: 

You want jQuery. See http://jQuery.org This can be accomplished using a "selector" (jquery term)

Tom Dignan