Javascript Dropdown Widget

I have a menu consisting of <ul> in web CMS. I want some menu items to have subitems that are displayed in a drop-down list. These subparagraphs are also equal.

This is basically easy to do with a few lines of CSS and Javascript, but I'm looking for a complete Javascript solution that helps me deal with the following:

  • Deal with extreme screen situations. If any part of the drop-down menu is outside the current viewport, position it so that it is completely in the viewport.

This is a bitch for code from scratch.

"It would be nice:

  • Centered positioning below the drop-down button

  • Adding an onclick event to the body, so clicking outside the drop-down menu will close it; net deletion of the onclick event afterwards

But I can do it if necessary.

A nice, small, unobtrusive widget that magically transforms my <ul> would be great.

If the solution is based on a framework, it should be Prototype like what I use in CMS.

+3
source share
1 answer

You can get UL offsets and check if they are a certain distance from the viewing area.

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

You can also get the exact position of the drop-down menu button, and then you need to apply basic math to position the menu below it.

+3
source

Source: https://habr.com/ru/post/1723547/


All Articles