Many website developers think of web pages as static objects. They are receptacles for images and text. However, there are actually a number of events continually occurring as a user views a web page. For example, a website user may: change the size of the browser viewing window; move the mouse cursor over different elements on the web page; enter information into a text box; click on elements.
Most of the time these events actually do nothing, but the web page programmer can change that a make use of the events by adding Javascript code that will monitor the events and then provide some response to the user, such as highlighting the element over which the user places their mouse cursor.
Starting to Use Browser Events
The browser events do nothing by default. The just happen quietly and in the background. However, these events can be passed to functions for processing, for example:
div id=list_item_a
onmouseover="javascript: highlightme (event);"
onmouseout="javascript: highlightme (event);"
div id=list_item_b
onmouseover="javascript: highlightme (event);"
onmouseout="javascript: highlightme (event);"
Here the onmouseover event (which fires when the mouse cursor is placed over a web page element) and the onmouseout event (which fires when the mouse cursor is moved away from a web page element) are monitored and the event is passed on to the 'highlightme' function:
function highlightme (e) {
var id = (e.srcElement) ? e.srcElement.id : e.target.id;
if (id!="") {
var el = document.getElementById (id);
el.style.backgroundColor = (e.type == "mouseout") ? "white" : "silver";
}
}
The aim of this function is to: turn the background of the div to silver when the mouse cursor is passed over it; turn the background of the div to white when the mouse cursor is moved away from it.
Identifying Event Types
Each event had a type associated with it and so, for example, the onmouseout event has a type of mouseout:
el.style.backgroundColor = (e.type == "mouseout") ? "white" : "silver";
The advantage of this, of course, is that the developer is able to produce a single function to handle multiple events.. In this case, both the onmouseout and onmouseover events.
Identifying the Source of the Event
Each event has an id property that contains the id of the element firing the event (assuming that the id has been set by the web page designer). However, as is often the case, the code for doing this varies according the the browser being used:
var id = (e.srcElement) ? e.srcElement.id : e.target.id;
In this way the web page programmer can monitor, and react to, any events that occur and provide a fully interactive experience for their website users.