![]() |
Event Delegation
This example demonstrates Event Delegation in JavaScript; or, at least, my interpretation of this topic ;)
Event delegation has two related meanings. In languages other than JS a delegate is an object that is created specifically to respond to an event on an object (or objects). The simpler meaning for this example is the following: Quote:
The following example attaches the click event to the (parent) ol-element. When this is clicked we respond to the event BUT ONLY FOR LI-ITEMS. The counter confirms that there is only one instance of the alertText() function. Code:
<!DOCTYPE html> |
Below is an expanded version that also passes arguments to the delegated event:
It will highlight rows as you mouseover them using a supplied colour argument, also (optionally) displaying the row number ("Row 1", etc.). When the mouse moves out the previous background colour is re-instated and the temporary title ("Row 1", etc.) is removed. Code:
<!DOCTYPE html> |
Code:
var addEvent = function (elem, eventType, func) { if ( elem.addEventListener ) addEvent = function (elem, eventType, func) { elem.addEventListener(eventType, func, false); }; else if ( elem.attachEvent ) addEvent = function (elem, eventType, func) { elem.attachEvent('on' + eventType, func); }; else addEvent = function (elem, eventType, func) { elem['on' + eventType] = func; }; addEvent(elem, eventType, func); };a browser that will execute the red code ? |
Quote:
|
| All times are GMT +1. The time now is 05:20 AM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.