Mouse Events

See sections 7B and 7H of the book.

The mouse events are by far the most important events. On this page I introduce some of the most common problems and tricks.

We’ll go through all mouse events: mousedown, mouseup and click, dblclick, mousemove and finally mouseover and mouseout. Then I explain the relatedTarget, fromElement and toElement event properties. Finally the Microsoft proprietary mouseenter and mouseleave events.

For browser compatibility, see the Event Compatibility Tables page.

Example

Here’s a small example. Try it to better understand the explanations below.
Mousedown, mouseup, click and dblclick are registered to the link. You’ll see the events that take place in the textarea, or in an alert, if you so choose.

The event handlers are registered on this link.
Clear textarea.

Show alert instead of writing to textarea

Mousedown, mouseup, click

If the user clicks on an element no less than three mouse events fire, in this order:

  1. mousedown, user depresses the mouse button on this element
  2. mouseup, user releases the mouse button on this element
  3. click, one mousedown and one mouseup detected on this element

In general mousedown and mouseup are more useful than click. Some browsers don’t allow you to read out mouse button information onclick. Furthermore, sometimes the user does something with his mouse but no click event follows.

Suppose the user depresses the mouse button on a link, then moves his mouse off the link and then releases the mouse button. Now the link only registers a mousedown event. Similarly, if the user depresses the mouse button, then moves the mouse over a link and then releases the mouse button, the link only registers a mouseup. In neither case does a click event fire.

Whether or not this is a problem depends on the user interaction you want. But you should generally register your script onmousedown/up, unless you’re completely sure you want the click event and nothing else.

If you use alerts in handling these events, the browser may lose track of which event took place on which element and how many times it took place, messing up your scripts. So it’s best not to use alerts.

Dblclick

The dblclick event is rarely used. Even when you use it, you should be sure never to register both an onclick and an ondblclick event handler on the same HTML element. Finding out what the user has actually done is nearly impossible if you register both.

After all, when the user double–clicks on an element one click event takes place before the dblclick. Besides, in Netscape the second click event is also separately handled before the dblclick. Finally, alerts are dangerous here, too.

So keep your clicks and dblclicks well separated to avoid complications.

Mousemove

The mousemove event works fine, but you should be aware that it may take quite some system time to process all mousemove events. If the user moves the mouse one pixel, the mousemove event fires. Even when nothing actually happens, long and complicated functions take time and this may affect the usability of the site: everything goes very slowly, especially on old computers.

Therefore it’s best to register an onmousemove event handler only when you need it and to remove it as soon as it’s not needed any more:

element.onmousemove = doSomething;
// later
element.onmousemove = null;

Mouseover and mouseout

Take another look at the example, switch the mouseovers on and try them. The example adds an onmouseover event handler to ev3 only. However, you’ll notice that a mouseover event takes place not only when the mouse enters ev3's area, but also when it enters the area of ev4 or the span. In Mozilla before 1.3, the event even fires when the mouse enters the area of a text!

The reason for this is of course event bubbling. The user causes a mouseover event on ev4. There is no onmouseover event handler on this element, but there is one on ev3. As soon as the event has bubbled up to this element, the event handler is executed.

Now this setup, though completely correct, gives us some problems. Our first problem is targeting. Suppose the mouse enters ev4:

-----------------------------------------
| This is div id="ev3"                  |
|   -----------------------------       |
|   | This is div id="ev4"      |       |
|   | --------              <--------   |
|   | | span |                  |       |
|   | |      |                  |       |
|   | --------                  |       |
|   -----------------------------       |
-----------------------------------------

<--------: mouse movement

Now the target/srcElement of this event is ev4: it’s the element the event took place on, since the user mouses over it. But when this happens:

-----------------------------------------
| This is div id="ev3"                  |
|   -----------------------------       |
|   | This is div id="ev4"      |       |
|   | --------                  |       |
|   | | span |                  |       |
|   | |    -------->            |       |
|   | --------                  |       |
|   -----------------------------       |
-----------------------------------------

-------->: mouse movement

the event has exactly the same target/srcElement. Here, too, the mouse enters ev4. Nonetheless you might want do one thing when the mouse comes from ev3 and another thing when it comes from the SPAN. So we need to know where the mouse comes from.

relatedTarget, fromElement, toElement

W3C added the relatedTarget property to mouseover and mouseout events. This contains the element the mouse came from in case of mouseover, or the element it goes to in case of mouseout.

Microsoft created two properties to contain this information:

In our first example, relatedTarget/fromElement contains a reference to ev3, in our second example to the SPAN. Now you know where the mouse came from.

Cross–browser scripts

So if you want to know where the mouse comes from in case of mouseover, do:

function doSomething(e) {
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.fromElement;
}

If you want to know where the mouse goes to in case of mouseout, do:

function doSomething(e) {
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.toElement;
}

Mousing out of a layer

In a layer-based navigation you may need to know when the mouse leaves a layer so that it can be closed. Therefore you register an onmouseout event handler to the layer. However, event bubbling causes this event handler to fire when the mouse leaves any element inside the layer, too.

--------------
| Layer      |.onmouseout = doSomething;
| --------   |
| | Link | ----> We want to know about this mouseout
| |      |   |
| --------   |
| --------   |
| | Link |   |
| |    ----> | but not about this one
| --------   |
--------------
---->: mouse movement

Another show stopper is that when you move the mouse into the layer, and then onto a link, browsers register a mouseout event on the layer! It doesn't make much sense to me (the mouse is still in the layer), but all browsers agree on this one.

So how do we reject any mouseout that does not take place when the mouse actually leaves the layer?

function doSomething(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
	if (tg.nodeName != 'DIV') return;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	while (reltg != tg && reltg.nodeName != 'BODY')
		reltg= reltg.parentNode
	if (reltg== tg) return;
	// Mouseout took place when mouse actually left layer
	// Handle event
}

First get the event target, ie. the element the mouse moved out of. If the target is not the DIV (layer), end the function immediately, since the mouse has certainly not left the layer.

If the target is the layer, we're still not sure if the mouse left the layer or entered a link within the layer. Therefore we're going to check the relatedTarget/toElement of the event, ie. the element the mouse moved to.

We read out this element, and then we're going to move upwards through the DOM tree until we either encounter the target of the event (ie. the DIV), or the body element.

If we encounter the target the mouse moves towards a child element of the layer, so the mouse has not actually left the layer. We stop the function.

When the function has survived all these checks we're certain that the mouse has actually left the layer and we can take appropriate action (usually making the layer invisible).

Mouseenter and mouseleave

Microsoft has another solution. It has created two new events mouseenter and mouseleave. They are almost the same as mouseover and mouseout except that they don’t react to event bubbling. Therefore they see the entire HTML element they’re registered to as one solid block and don’t react to mouseovers and –outs taking place inside the block.

So using these events solves our problem too: they react only to mouseovers/outs on the element they’re registered to.

At the moment these events are only supported by Explorer 5.5 on Windows and higher. Maybe the other browser vendors will copy these events.

End

You have now reached the end of my Introduction to Events. Good luck in writing your own event handling scripts.