JavaScript: Delegating focus and blur events

Peter-Paul Koch is working on event delegation. Event delegation is especially useful in effects like dropdown menus, where lots of events on links may take place that can easily be handled at the root level (an <ol>or <ul>in this case). What is event delegation? For those unaware of it, let's briefly discuss event delegation. As […]

Peter-Paul Koch is working on event delegation. Event delegation is especially useful in effects like dropdown menus, where lots of events on links may take place that can easily be handled at the root level (an <ol>or <ul>in this case).

What is event delegation?

For those unaware of it, let's briefly discuss event delegation. As context I'll use a dropdown menu.

When a user uses a mouse to steer through a dropdown menu, you want to capture all mouseover and mouseout events in order to see whether the latest user action should open or close a menu. (You also have to carefully distinguish between useful and useless events because Firefox, Safari and Opera still don't support the mouseenter and mouseleave events, but that's another story.)

The mouseover and mouseout events bubble up; that is, when a mouseover event on a link fires, the event "climbs" the DOM tree to see if any mouseover event handlers are defined on the ancestor nodes of the link. It first checks the link itself, then goes on to the containing <li>, followed by the <ol>, and all the way up to document or window level.

That means that it's perfectly possible to define your generic onmouseover and onmouseout event handlers on the <ol>that forms the root element of the dropdown menu. When these events take place lower in the tree, event bubbling makes sure they eventually end up at the root element and can be handled there.

<ol id="dropdown">
	<li>List item 1
		<ol>
			<li>List item 1.1</li>
			<li>List item 1.2</li>
			<li>List item 1.3</li>
		</ol>
	</li>
	[etc.]
</ol>

$('dropdown').onmouseover = handleMouseOver;
$('dropdown').onmouseout = handleMouseOut;

More info: Delegating the focus and blur events

JavaScript, Browser, Unobtrusive, Focus, Blur, HTML