Friday 19 October 2007

Creating hover menus and closing them with Javascript + Prototype

First of all I created an empty div that will be used to contain my menu contents. For example,

<div id="accesslist" class="accessmenu">Hello there!</div>

With CSS,


div.accessmenu {
position: absolute;
background: #F5F5F5;
border: 1px solid #888;
margin: 0;
padding: 3px;
visibility: hidden;
}

Now it's up to you how you want to position the menu, but this is how I did it with Javascript.

$('accesslist').style.left = Position.positionedOffset(el)[0];
$('accesslist').style.top = Position.positionedOffset(el)[1] + el.offsetHeight;
$('accesslist').style.zIndex = 10;
$('accesslist').style.visibility = 'visible';

The code above will place the div directly below element 'el'. Now the problem is how do you close the menu when you click away from it? A simple solution can be found using prototype's Event class.

Event.observe(document.body, 'click', function(e) {
if (!Element.descendantOf(Event.element(e), $('accesslist')))
$('accesslist').style.visibility = 'hidden';
});

What this code does is that it observes 'click' events that occur on the document.body. The third function parameter checks if the event click happened on my menu element's descendants (i.e. down the tree hierarchy). If not, then close the menu.

Simple.

No comments: