Sednus
Sednus

Reputation: 2113

Setting event handlers to DOM objects

I was looking for the most proper way to attach DOM events avoiding browser compatibility issues and found that the Mozilla developers site states:

The old way is to just assign it like this:

document.getElementById('cupcakeButton').onclick = getACupcake;

As above, the event object is either a global or an argument. This method may have problems and is not the preferred method, but it still works and a lot of people still use it.

What type of problems does this refer to?

Upvotes: 1

Views: 90

Answers (2)

Mathijs Flietstra
Mathijs Flietstra

Reputation: 12974

The most obvious one is already mentioned, it would replace a previously assigned handler.

document.getElementById('id') should work in all browsers except in really old ones (Netscape 4-, IE 4-), there you should use document.layers['id'] and document.all[id] respectively.

IE 5 up to IE 7 have one more issue, which is that they will also return elements where name='id' instead of only the elements where id='id'. That could really stuff you up.

Have a look at jQuery for a way to attach DOM event handlers avoiding browser compatibility issues.

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173662

The biggest problem I can think of is that it won't allow assigning multiple click handlers, by doing another .onclick = fn; you basically unbind the previous handler if it was there.

Even if that magically worked, you would have no way to unregister a specific handler; it's all or nothing.

Upvotes: 1

Related Questions