Skip to content

Rollovers using the Motionbox EventHandler

by Topper on April 30th, 2008

YUI has yet another nice writeup on unobtrusive rollovers.

I wanted to take a sec and show you how cleanly we’ve implemented it using our bubbling library: the Motionbox EventHandler.

[js]
var handleMouseover = function (evt) {
var el = evt.element();
var movingFrom = evt.relatedTarget;

var isMouseover = false; // is this event a move from the outside to the inside?
if (el.hasClassName(‘responds_to_mouseover’)) {
isMouseover = !movingFrom || !movingFrom.descendantOf(el);
}
else if (el.up(‘.responds_to_mouseover’)) {
el = el.up(‘.responds_to_mouseover’);
isMouseover = !movingFrom || (movingFrom !== el && !movingFrom.descendantOf(el));
}

if (isMouseover) {
el.addClassName(“mouseover”);
}
};

var handleMouseout = function (evt) {
var el = evt.element();
var movingTo = evt.relatedTarget;

var isMouseout = false; // is this event a move from the inside to the outside?
if (el.hasClassName(‘responds_to_mouseover’)) {
isMouseout = !movingTo || !movingTo.descendantOf(el);
}
else if (el.up(‘.responds_to_mouseover’)) {
el = el.up(‘.responds_to_mouseover’);
isMouseout = !movingTo || (movingTo !== el && !movingTo.descendantOf(el));
}

if (isMouseout) {
el.removeClassName(“mouseover”);
}
};

MOBX.EventHandler.subscribe(“.responds_to_mouseover”, “mouseover”, handleMouseover);
MOBX.EventHandler.subscribe(“.responds_to_mouseover”, “mouseout”, handleMouseout);
[/js]
(thanks to Matt Royal for figuring out the ins and outs of some kinks to this)

Then you can just create any element you want (in any browser) and add the class “responds_to_mouseover” to it.

[html]

I respond to mouseover

[/html]

As you hover over that div or leave that div the class “mouseover” gets added or removed from it. You can then use CSS to style the states appropriately.