Working on an application that had heavy use of multiple-tiered custom context menus, and needed to position sublevels based on it’s net position relative to the viewport (if there’s not room on the right of the originating element, position it to the left – same with top/bottom).

Here’s the MooTools version…

Takes either ‘x’ or ‘y’ as an argument (will the element fit horizontally or vertically) – omit the argument to test both.

jQuery version will follow.