views:

148

answers:

1

I have a menu consisting of an <ul> in a Web CMS. I want several menu items to have sub-items that are displayed in a dropdown list. These sub-items are <ul>s as well.

This is basically easy to do with a few lines of CSS and Javascript, but I am looking for a ready-made Javascript solution that helps me handle the following:

  • Deal with screen edge situations: If any part the dropdown menu would be outside the current viewport, place it so that it is completely within the viewport.

This is a bitch to code from scratch.

"Nice to have"s would be:

  • Centered positioning below the drop-down button

  • Adding a onclick event to the body so that clicking outside the drop down menu will close it; clean removal of the onclick event afterwards

But those I can do myself if necessary.

A nice, small, unobtrusive widget that magically converts my <ul> would be lovely.

If the solution is based on a framework, it has to be Prototype as that's what I'm using in the CMS.

+1  A: 

You can get the offsets of the UL, and check whether those are in a certain distance of the viewport.

// Pseudo code
var ul = document.getElementById("menu");
if(ul.offset.x + ul.width > viewport.width) {
    ul.offset.x = viewport.width - ul.width;
}

It's also possible to get the exact position of the dropdown button clicked, and then you should apply basic math in order to position the menu beneath it.

Matthias Vance
Yes, that's the way to go. I know however from previous experience, that getting this right (taking into consideration scrollable containers, absolute / relative positioning and whatnot), and then making it work in all browsers, tends to eat up a lot of time. I would love to get around that :)
Pekka
In that case a library would really help, unfortunately I cannot help you with those, because I tend to use my own libraries.
Matthias Vance
I rolled my own in the end.
Pekka