↑
Main Page
Internet Explorer
Using this method of assignment, the event handler name must be represented in all lowercase letters to
properly respond to the event.
To assign an event handler in HTML, you simply add an event handler attribute to the HTML tag and
include the appropriate script as the attribute value, like so:
<div onclick=”alert(‘I was clicked’)”></div>
With this method, the event handler can have any case, so
onclick
is equal to
onClick
,
OnClick
, and
ONCLICK
. (However, if you are using valid XHTML code, event handlers should be defined using all
lowercase letters.)
When you are assigning event handlers in HTML, remember that the code contained in the attribute
value (between the quotes) is wrapped in an anonymous function, so the HTML code actually executes
the following JavaScript:
oDiv.onclick = function () {
alert(“I was clicked”);
};
Look familiar? Yes, it is the same code as the JavaScript example.
These methods both work in all modern browsers, but additional methods can make more than one
event handler per event available. Once again, Internet Explorer contains a proprietary method whereas
the DOM prescribes another.
Internet Explorer
In IE, every element and
window
object has two methods:
attachEvent()
and
detachEvent()
. As the
names indicates,
attachEvent()
is used to attach an event handler to an event and
detachEvent()
is
used to detach an event handler. Each method takes two arguments: the name of the event handler to
assign to (for example:
onclick
) and a function.
[Object].
attachEvent(“name_of_event_handler”, fnHandler);
[Object].
detachEvent(“name_of_event_handler”, fnHandler);
In the case of
attachEvent()
, the function is added as an event handler; for
detachEvent()
, it looks
for the given function in the event handler list and removes it. For example:
var fnClick = function () {
alert(“Clicked!”);
};
var oDiv = document.getElementById(“div”);
oDiv.attachEvent(“onclick”, fnClick); //add the event handler
//do some other stuff here
oDiv.detachEvent(“onclick”, fnClick); //remove the event handler
267
All about Events
12_579088 ch09.qxd 3/28/05 11:39 AM Page 267
Free JavaScript Editor
Ajax Editor
©
→