This page has been translated using an automatic translation service and the translation may not be very accurate.

I use of the events in Javascript (English)

If you use this code and feel it is a useful tool, consider making a donation (through PayPal) to help support the project. You can donate as little or as much as you wish, any amount is greatly appreciated!

Italian page For the original Italian page, please click on the link: http://www.guru4.net/articoli/javascript-events/default.aspx

Like all the main models to objects, also the Object Model di Dynamic HTML (DHTML) essentially is characterized gives:

  • Constants, like table colors, HTTP Response Headers, table codes of a specific language, etc.

  • Collections, like as an example childNodes (collection of elements HTML and TextNode that come down from a specific object), attributes (the directory of the attributes of an object), images (the collections of contained images in a document), etc.

  • Objects, that is the single ones "mattoncini" that they constitute the DOM of a document, typically inserted through markup like body, img, form, etc.

  • Methods, like alert for the visualization of a applicativa window of dialogue, appendChild that it concurs to extend the collection of the childNodes of an object, createElement for istanziare a new element for a specific one tag, etc.

  • Property, that they concur to specify - typically like attributes in the markup - characteristic detailed lists of an object like background, border, font, title, width, height, etc.

  • Events, that is the modality with which an object notification to the outside that "has succeeded something", like a change of the state (like as an example load, error, etc.) or the action of a customer or an other element of the DOM (like as an example click, focus, blur, etc.)

In this article we will stop ourselves in particular on I use of the events, analyzing the various methods available in order to intercept the events and to associate the code to you necessary Javascript to the operation of an application web-based.

Event handling

Various modalities exist in order to intercept an event (event handling). Of continuation they come proposed the main solutions available:

Management of the events through markup

The handling of an event through markup it is probably the diffused modality more:

<input type="button" value="Hello" onclick="alert('Hello World!');" />

That it produces the following element:

Management of the events through code Javascript

Through Javascript it is possible to associate to an event of a specific object the execution of a particular code:

<input type="button" value="Hello" id="btnHello1" />

<script type="text/javascript">

document.getElementById("btnHello1").onclick = function()
{
    alert("Hello World!");
}

</script>

That it produces:

In analogous way we can associate to an event the execution of specific function:

<input type="button" value="Hello" id="btnHello2" />

<script type="text/javascript">

document.getElementById("btnHello2").onclick = HelloWorld;

function HelloWorld()
{
    alert("Hello World!");
}

</script>

You notice the absence of the round parentheses in the association of the function to the event (function pointer)

That it produces:

Management of the events through Object Model: addEventListener/attachEvent

This last one is decidedly the better modality in order to record an event in how much:

  • it not only can be used with whichever element of the DOM and with elements HTML

  • better management of the code executed in correspondence of get loosing itself of an event supplies one (capturing vs. bubbling)

  • it concurs to manage more handler for the same event; that is particularly useful in the development of generic bookcases (or Web User Control), where a management of the events through markup or gunlayers to function could create problems of sovrascrittura of handler sets up to you from the page or other controlli/librerie directly (as an example imagines the typical case of initialization of a member who demands the load complete of the DOM: to associate it sovrascrivendo the event onload of the body could compromise the execution of the rest of the page!)

Standard W3C previews the use of:

target.addEventListener(type, listener, useCapture);

Where:

  • target: the object of which it is desired to intercept the event

  • type: it tightens that it represents the type of event to intercept

  • listener: the object that receives the notification when the event comes triggered; it must implement a EventListener interface or, more simply, to be a punatore to one function Javascript.

  • useCapture: if "true" all the events of the specific type will be managed from the listener indicated before coming iniviati to the elements in the hierarchy of the DOM; for greater details it is sent back to DOM Level 3 Events

In Microsoft Internet Explorer Rather than addEventListener it is used:

bSuccess = object.attachEvent(sEvent, fpNotify);

Where:

  • object: the object of which it is desired to intercept the event

  • sEvent: it tightens that it represents the type of event to intercept

  • fpNotify: the punatore to the function Javascript that is desired invoca to get loosing itself of the event.

  • bSuccess: (return) a booleano value that it indicates if the event has been correctly associated to the specific function

It is therefore important to notice like the Object Model of DHTML depends strongly on the platform used (typically from the browser in which it comes loaded the document); for the realization of independent applications from the platform it is therefore necessary to only use the elements (objects, collections, methods, property and events) totally supports from all the browser to you of reference.

In order to implement correctly the management of the events being used the DOM is therefore necessary to entrust itself to a control based on the browser-capabilities:

<input type="button" value="Hello" id="btnHello3" />

<script type="text/javascript">

var btn = document.getElementById("btnHello3");

if (btn.addEventListener)
    btn.addEventListener("click", HelloWorld, false);
else if (btn.attachEvent)
    btn.attachEvent("onclick", HelloWorld);

function HelloWorld()
{
    alert("Hello World!");
}

</script>

That it produces:

In analogous way it is possible to remove a event handler using removeEventListener (W3C Standard) or detachEvent (Internet Explorer).

Like already pointed out previously, one of the greater advantages deriving from the use of addEventListener (or attachEvent in the IE case) it is that it allows to associate handler to events already intercepts to you without to compromise of the operation:

<input type="button" value="Hello" id="btnHello4" onclick="alert('onclick da markup');" />

<script type="text/javascript">

var btn = document.getElementById("btnHello4");

if (btn.addEventListener)
    btn.addEventListener("click", function(){alert("onclick da addEventListener");}, false);
else if (btn.attachEvent)
    btn.attachEvent("onclick", function(){alert("onclick da attachEvent");});

</script>

In this way the push-button:

it executes correctly is the code associated to the event "onclick" from markup, is that associate through DOM