Most JavaScript-applications perform actions as a response to events.
An event is a signal from the browser that something has happened.
There are many types of events.
DOM events, which are initiated by DOM-elements. For instance, a click event happens when an element is clicked, a mouseover - when a mouse pointer comes over an element,
Window events. For instance, resize - when a browser window is resized,
Other events, like load, readystatechange. They are used in AJAX and for other needs.
DOM events connect JavaScript code with the document, providing the means for building dynamical interfaces.
Assigning event handlers
For a script to react on the event, there should be a function assigned to it.
Functions which react on events are called event handlers. They are usually named like "on+event type", for instance: onclick.
JavaScript event handling is single-threaded, so handlers are executed sequentially. That means, if two events happen simultanteously, for example mouseover (mouse has come over an element) and mousemove (mouse moved over an element), their handlers will be executed one after another.
There are several ways of assigning an event handler. All of them are given in details below.
Using a attribute of HTML-tag
A handler can be set directly in the markup, right into the attribute named onevent.
For example, to process a click event on the input button, it is possible to assign an onclick handler like this:
The last example uses single quotes inside double quotes. An often newbie mistake is to forget that the code is inside an attribute.
Using them like onclick="alert("Click")" won’t work. If you really need it, tryonclick="alert("Click")". But usually you don’t. Read on for more event handling methods.
It is also possible to call a function for the event handling. The example below runs a function count_rabbits() if a button is clicked.
The difference is easy to explain. When the browser comes across onclick attribute, it automatically creates a function from its contents. So the last example is basically same as:
A convenient and reliable way, works in JavaScript
A single handler per event
Of course, it’s possible to copy old handler and run it manually inside a new one. But it is better to use more advanced methods of assignment.
Special methods
In a complex JavaScript application, it’s fairly ok that different interface components may be interested in handling the same event.
A classical example is a “document loaded” event and many graphical components which wait for it to initialize themselves.
Microsoft solution
The solution provided by Microsoft and used only in Internet Explorer less than 9.
It is also supported by Opera for compatibility, but no one uses it there, because Opera also supports another standard-compliant method (see in the next section).
Assigning a handler:
element.attachEvent( "on"+event, handler)
Removing a handler:
element.detachEvent( "on"+event, handler)
For instance:
1
varinput = document.getElementById('button')
2
functionhandler() {
3
alert('Thanks!')
4
}
5
input.attachEvent( "onclick", handler) // assign the handler
6
// ....
7
input.detachEvent( "onclick", handler) // remove the handler
An often newbie mistake
Please, note - setting and removal methods need the same handler object to operate correctly.
This would be wrong:
1
input.attachEvent( "onclick",
2
function() {alert('Thanks')}
3
)
4
// ....
5
input.detachEvent( "onclick",
6
function() {alert('Thanks')}
7
)
In the example below, there are actually two different function objects.
So if it is planned to remove the handler sometime, the reference to it should be stored somewhere.
Using attachEvent, it is possible to assign multiple handlers to the same event on same element. The example below will work only in IE and Opera:
Please, note that the event name goes without the “on” prefix.
Another difference from the Microsoft syntax is the third parameter - phase, which is usually not used and set to false.
The usage is generally same as attachEvent:
1
// ... declare a function called handler ...
2
elem.addEventListener( "click", handler, false) // assign the handler
3
// ....
4
elem.removeEventListener( "click", handler, false) // remove the handler
So, there is a one big plus and one minus of the special methods:
As many handlers as you want
Cross-browser incompatibilities
The incompatibilities is not just different syntax, but there are few other differences. We’ll return to it in the next sections and discuss a cross-browser method of event handling.
Handlers order
Special methods allow to assign multiple handlers to the same event on single object.
Browser does not guarantee the order in which they execute.
Generally, the order of assignment is not related with the order of execution. The order may happen to be same, or inversed or random.
A cross-browser way of assigning event handlers
The task is not so simple as it seems.
There simplest and mostly working solution is to create custom functions which add and remove event handlers using special methods: