📜 ⬆️ ⬇️

Convert menu to drop-down list on small screens

image

As an example of what we get as a result, you can see the website “Five Simple Steps” with adaptive layout. When the browser window has a small width, the menu in the upper right corner is transformed from a regular row of links into a drop-down menu.

When viewing the site on a small display (phone), by clicking on the drop-down menu, you will see an interface for selecting a menu item where each item is large and easy to select.

image
')
This is undoubtedly easier than trying to get a finger on a small link on the phone screen. Of course, you will have to click on the screen 2 times instead of once, but this is a controversial drawback, since, in the opposite case, you will first have to enlarge the page, and only then click on the link.

HTML


This is how the markup of this menu on the Five Simple Steps site looks like:
<nav> <ul> <li><a href="/" class="active">Home</a></li> <li><a href="/collections/all">Books</a></li> <li><a href="/blogs/five-simple-steps-blog">Blog</a></li> <li><a href="/pages/about-us">About Us</a></li> <li><a href="/pages/support">Support</a></li> </ul> <select> <option value="" selected="selected">Select</option> <option value="/">Home</option> <option value="/collections/all">Books</option> <option value="/blogs/five-simple-steps-blog">Blog</option> <option value="/pages/about-us">About Us</option> <option value="/pages/support">Support</option> </select> </nav> 

CSS


By default, we need to hide the menu using display: none; .
 nav select { display: none; } 

Then, using media queries, we will switch the visibility of the select element and the regular menu depending on the width of the screen.
 @media (max-width: 960px) { nav ul { display: none; } nav select { display: inline-block; } } 

Sync menu items with jQuery


Perhaps your menu is created dynamically, perhaps you are creating the menu manually, but it is always helpful to be sure that the menu items on both menus are similar. To achieve uniformity of both menus, we will use dynamic drop-down menu creation based on the original menu.

This is possible using the following jQuery code:
 //      $("<select />").appendTo("nav"); //   select   – « ...» $("<option />", { "selected": "selected", "value" : "", "text" : " ..." }).appendTo("nav select"); //          $("nav a").each(function() { var el = $(this); $("<option />", { "value" : el.attr("href"), "text" : el.text() }).appendTo("nav select"); }); 

And in the end - the code to make the drop-down menu work:
 $("nav select").change(function() { window.location = $(this).find("option:selected").val(); }); 

Watch the demo
Download an example

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


All Articles