New Revised CSS Library Forums Web Tools
FAQs Awards Usage Terms Contact
Categories
Other Sections
Sweet Ads
Compatibility
Bookmark online:


FF1+ IE7+ Opera8+

Smooth Navigational Menu (v3.0)

Author: Dynamic Drive

Updated: Update March 17th, 15' to v3.0: Adds fully mobile friendly, compact version of menu that's activated in mobile and small screen browsers. Refines drop down menu behaviour when there's neither space to the right nor left to accommodate sub menu; in that case sub menu overlaps parent menu.

Description: Smooth Navigation Menu is a multi level, CSS list based menu powered using jQuery that makes website navigation a smooth affair. And that's a good thing given the important role of this element in any site. The menu's contents can either be from direct markup on the page, or an external file and fetched via Ajax instead. And thanks to jQuery, a configurable, sleek "slide plus fade in" transition is applied during the unveiling of the sub menus. The menu supports both the horizontal and vertical (sidebar) orientation. On the mobile front (v3.0+), the menu transforms into a fixed, vertical menu when the user's device or browser screen is below a certain width, ensuring a smooth experience regardless of screen size.

Some noteworthy features- You can specify a delay before the sub menus appear and disappear when the mouse rolls over and out of them, respectively. The sub menus reposition themselves if too close to the window's right edges. And last but not least, the depth of the accompanying shadow can be customized, or removed altogether. Smooth we say!


Directions Developer's View

Step 1: Insert the following code into the <head> section of your page:

Select All

The above code references a few external files, which by default you should upload to the same directory as the page itself (right click each file and select "Save As"):

Step 2:  Add the below menu code to the BODY section of your page. It contains the markup for 1 horizontal menu and 1 vertical menu:

Select All

Each menu should consist of an outer DIV and a valid UL list contained inside it.

If you wish the menu content to reside in an external file on your server and dynamically added to your page(s), read the section "Putting the Menu contents in an external file" below.

Well, that's it for installation.

ddsmoothmenu.init() and Menu content structure

Setting up a Smooth Navigational Menu on your page involves calling ddsmoothmenu.init() inside the HEAD section of your page:

ddsmoothmenu.init({
 mainmenuid: "smoothmenu1", //menu DIV id
 orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
 classname: 'ddsmoothmenu', //class added to menu's outer DIV
 //customtheme: ["#1c5a80", "#18374a"],
 contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})

where "smoothmenu1" corresponds to the menu content's outermost DIV on the page. Here's a description of each option:

Option Description
mainmenuid The ID of the menu's outermost DIV. If the menu contents are fetched via Ajax, then this ID should correspond to the outermost DIV that's within the external file.
orientation Sets the orientation of the menu. Enter the value "h" or "v" for a horizontal or vertical menu, respectively. Note that the "classname" setting below must also be set according to the "orientation" setting.
classname Sets the CSS class name that gets applied to the outermost DIV of the menu, effectively styling it. Based on the "orientation" setting above, you want to enter the CSS class that correctly styles the menu By default, "ddsmoothmenu" creates a horizontal menu bar, while "ddsmoothmenu-v" creates a vertical one. Take a look inside ddsmoothmenu.css and ddsmoothmenu-v.css.
method

v2.0 option

Sets the method for which the sub menus should open and close, either "hover" or "toggle". Defaults to "hover", which opens each sub menu when the user rolls the mouse over it. With "toggle", the menus are opened when the user clicks on them instead.
arrowswap

v2.0 option

Boolean that if set to true (defaults to false) will cause the script to show alternate versions of the arrow images (down and right) of the menu when the mouse rolls over a menu header. In other words, it enables rollover effect on the arrow images.

You do NOT specify the paths to the rollover images when this option is enabled. Instead, the script simply looks at the path and file names of the default arrow images inside ddsmoothmenu.js and appends a "_over" suffix to the default images' file names to form the full path and file names to the rollover images. So if the paths to the default arrow images as specified inside ddsmoothmenu.js are as follows:

arrowimages: {down:['downarrowclass', 'images/down.gif', 23], right:['rightarrowclass', 'images/right.gif', 6]},

In this case you should name your rollover images down_over.gif and right_over.gif respectively, and place them inside the images/ directory.

customtheme In general, customizing the menu's style and background colors is done by editing the two CSS files of the script. However, you can also modify the menu's background and hover background color- on a per page or per menu basis easily, by taking advantage of the "customtheme" setting. To do so, uncomment (remove the // prefix) from this setting and declare two CSS background values, one for the default state, the other, when the mouse rolls over the menu items:

customtheme: ["#1c5a80", "#18374a"], //override default menu CSS background values?

This property is useful for quickly testing out color combinations without having to edit "ddsmoothmenu.css" each time.

contentsource Enter "markup" if your  menu contents are directly inline on the page, or ["container_id", "path_to_menu_file"] For more info on the later option, see "Putting the Menu contents in an external file and fetched using Ajax" below.

Menu content structure

As far as the HTML markup of each menu, it should consist of an outer DIV plus a valid UL list inside it, such as:

<div id="smoothmenu1">
 <ul>
 <li><a href="http://www.dynamicdrive.com">Item 1</a></li>
 <li><a href="#">Folder 0</a>
  <ul>
  <li><a href="#">Sub Item 1.1</a></li>
  <li><a href="#">Sub Item 1.2</a></li>
  </ul>
 </li>
 </ul>
</div>

Make sure the UL list is valid You can use W3C's validation service to quickly check your HTML list for incorrectly nested or unclosed tags.

Putting the Menu contents in an external file and fetched using Ajax

Instead of the menu's content being direct markup on the page, you can instead put that HTML in an external file on your server and have the menu dynamically added to the BODY of your page using Ajax. The above menu is embedded this way. The process for this is simple enough:

  1. Move the entire menu's HTML markup- including the outermost DIV container- to an external file on your server. For example: "smoothmenu.htm"
  2. On your page(s) themselves where you want the menu to be dynamically added, add an empty DIV container with a unique ID of its own in the BODY section of the page:

    <div id="smoothcontainer">
    <noscript>
    <a href="link to site map for search engines and user with JS disabled">Site map</a>
    </noscript>
    </div>

    This container's contents will be replaced by the menu contents defined in your external file when ddsmoothmenu.init() is run. You can include any HTML within this empty container that you may want shown to search engines or users with JavaScript disabled, as it will be replaced when the script is run.
  3. Finally, you need to edit ddsmoothmenu.init()'s "contentsource" setting to the appropriate setting :
     
    ddsmoothmenu.init({
    mainmenuid: "smoothmenu-ajax",
    //customtheme: ["#1c5a80", "#18374a"], //override default menu CSS background values? Uncomment: ["normal_background", "hover_background"]
    contentsource: ["smoothcontainer", "smoothmenu.htm"] //"markup" or ["container_id", "path_to_menu_file"]
    })

    The path to the external file, in this case "smoothmenu.htm", should be a relative path to it based on the current page's position within your site.

Styling the menu item the user is currently at

When the user rolls over a menu item (LI element) that contains a sub menu (UL element), the script dynamically adds a CSS class of ".selected" to the former's inner A element. This allows you to style the current active menu item differently from the rest. Inside "ddsmoothmenu.css", the relevant CSS you'll want to tweak is:

.ddsmoothmenu ul li a.selected { /*CSS class that's dynamically added to the currently active menu items' LI A element*/
 background: black !important;
 color: white;
}

Notice the !important declaration next to some of the properties inside the CSS file.  You may  need to experiment with adding or removing this declaration to the color related properties (background and color properties) inside the file to get the desired look.

Global menu settings

Finally inside ddsmoothmenu.js there are a few global settings you can modify, such as setting the paths to the arrow images, speed of animation, and whether to disable shadows:

mobilemediaquery: "screen and (max-width: 900px)", // CSS media query string that when matched activates mobile menu (while hiding default)
//Specify full URL to down and right arrow images (23 is padding-right for top level LIs with drop downs, 6 is for vertical top level items with fly outs):
arrowimages: {down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif', 6]},
transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
mobiletransition: 200, // duration of slide animation in mobile menu, in milliseconds
shadow: true, //enable shadow? (offsets now set in ddsmoothmenu.css stylesheet)
showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively
zindexvalue: 1000, //set z-index value for menus
closeonnonmenuclick: true, //when clicking outside of any "toggle" method menu, should all "toggle" menus close?
closeonmouseout: false, //when leaving a "toggle" menu, should all "toggle" menus close? Will not work on touchscreen The last line above lets you specify the delay before the sub menus appear and disappear when the mouse rolls over and out of them, respectively.

The two highlighted options in red pertain to mobile related settings, which is incidentally what we'll look at in detail next.

Configuring the mobile portion of the menu

Smooth Navigational Menu whether in "horizontal" or "vertical side bar" mode converts to a central, mobile optimized compact list menu when the desired criteria is matched. The following screenshot shows what happens when a page containing a horizontal and vertical Smooth Menu is resized below the mobile breaking point:


Screenshot

As you can see, when the threshold is met, both regular menus disappear, replaced by a drawer icon that when clicked on activates a compact list menu containing all of the combined menus' contents. The original menus reappear when that process is reversed. Whether you only have one Smooth Menu on your page or multiple menus, the outcome is the same. All facets of the mobile menu are dynamically generated, drawing upon existing markup for the regular menus, so there's no redundant code to add to your page. The only extra markup you need to add to  your page is the mobile menu "toggler" that toggles the visibility of the mobile menu in "mobile" mode, which is explained further below.

- Setting the mobile threshold

Before anything else you'll want to set the threshold when the user's environment is considered to be in "mobile", so the mobile version of the menu is activated. Inside ddsmoothmenu.js, modify the line:

mobilemediaquery: "screen and (max-width: 700px)", // CSS media query string that when matched activates mobile menu (while hiding default)

The portion in red should be a valid CSS media query to match when the menu switches over to the mobile version. Some examples of valid CSS media queries are as follows:

  • screen and (max-width: 700px)  //when the browser width is 700px or below, desktop or mobile alike
  • screen and (max-device-width: 480px)  //when the device width is 480px or below, which usually only means in mobile environments
  • screen and (max-device-width: 480px) and (orientation: portrait)  // when device width is 480px or below and in portrait mode only

The most common decision to make is whether to use max-width or max-device-width- the former means the value set applies to both desktop and mobile browsers, while the later limits the resulting match to only mobile devices, with desktop browsers always showing the regular menu.

IMPORTANT: Your page should carry the META tag <meta name="viewport" content="width=device-width, initial-scale=1"> in the HEAD section of your page to ensure the best mobile experience with this menu. This META tag instructs mobile browsers not to zoom out when rendering the webpage by default, which will lead to CSS media queries not being matched properly if the page is.

- Defining/ customizing the mobile menu toggler

The only markup you need to manually add to your page to take advantage of the mobile features of the menu is a mobile menu toggler link, which looks like the following:

<a class="animateddrawer" id="ddsmoothmenu-mobiletoggle" href="#">
<span></span>]\
</a>

The link should carry a CSS class of "animateddrawer" and ID of "ddsmoothmenu-mobiletoggle" exactly as is. You can place the toggle anywhere on your page you see fit. The style of this primary toggler is defined by the CSS class "animateddrawer" inside "ddsmoothmenu.css" at the bottom, under "Animated Drawer icon (mobile menu toggler) CSS".  The default style has it positioned at the upper right corner of the page and fixed when visible:

.animateddrawer{
font-size: 10px; /* Base font size. Adjust this value to modify size of drawer icon */
width: 3em;
height: 2.8em;
outline: none;
position: fixed; /* By default, make toggler fixed on screen */
display: none;
top: 10px; /* Position at upper right corner */
right: 10px;
background: white;
z-index: 1000;
}

"
"

When the mobile menu is open, an additional CSS class of "open" is added to the toggler link to let you style the link differently based on the menu state.

- Creating arbitrary links that toggle the mobile menu

Besides relying on the primary mobile toggler discussed above, you can also open/close the mobile menu on demand using arbitrary links you define on the page, such as:

<a href="#" onClick="return ddsmoothmenu.togglemobile()" ontouchstart="event.cancelBubble=true">Open/ Close Mobile Menu</a>

The code in red highlights what needs to be added inside your link for the process to work. For those puzzled by the code ontouchstart="event.cancelBubble=true, it is necessary in order to override another behaviour of the mobile menu, which is to dismiss the menu whenever the user clicks or taps anywhere on the page. Without the aforementioned code, the link will have no effect on the menu even though it's calling the appropriate method, ddsmoothmenu.togglemobile().

- Modifying the style of the mobile compact list menu

The style of the mobile compact menu is determined by the CSS class "div.ddsmoothmenumobile" that's added to the outermost container of the menu. To modify the style, go into "ddsmoothmenu.css" under "Mobile Menu container CSS".