The Concept
The latest mobile version of apple.com website has a very interesting use of navigation menu. It is horizontal, rather than the usual vertical, making use of the mobile, touch and drag horizontal scrolling. This might have been used by other websites, so please leave a comment on reddit if you see one.
We'll try to build a similar menu here, using a little bit of JavaScript. You can see the finished example at the top of this article, just click on the MENU button.
The HTML
The markup can be as complex as your needs, we will keep it simple. The idea is to have a main header that is always visible, and a hidden navigation bar, which will show when clicking on the menu button.
<header class="h-menu-header">
<div class="header">
<a href="/blog/2014/10/12/horizontal-menu" class="logo">Demo</a>
<button class="h-menu-btn" id="h-menu-btn">Menu</button>
</div>
<nav class="h-menu-subheader" id="h-menu-navbar">
<ul>
<li><a href="#concept">The concept</a></li>
<li><a href="#html">The HTML</a></li>
<li><a href="#css">The CSS</a></li>
<li><a href="#js">The JavaScript</a></li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
</nav>
</header>
We have also placed a button with id h-menu-btn
to toggle the menu. The links point at sections on the same page, but you could have any links you like.
The CSS
The stylesheet hides the subheader, and sets some basic styling for the list.
.h-menu-subheader {
position: absolute;
width: 18em;
display: none;
background: #888;
padding: 1em;
overflow: hidden;
overflow-x: auto;
}
.h-menu-subheader ul {
width: 200%;
}
.h-menu-subheader li {
display: inline-block;
margin-left: 1em;
}
.h-menu-subheader a {
color: #ddd;
}
.h-menu-subheader a:hover {
color: #fff;
}
.open .h-menu-btn {
color: #fff;
}
.open .h-menu-subheader {
display: block;
}
The subheader element has overflow-x
property as auto
, allowing the menu elements (within a an ul
with a set width of 150%) to scroll horizontally. In OS X, and mobile phones, the scrollbars are invisible, which makes the scrolling effect quite nice. In devices that show the scrollbars, we can use tricks, and jQuery plugins like perfect-scrollbar, jScrollPane to hide or customize them.
The JavaScript
Now we just need to show/hide the menu when the Menu button is clicked. We do that by adding a open
class to the parent element (declared earlier in CSS):
HorizontalMenu = function() {
this._init();
};
HorizontalMenu.prototype = {
_init: function() {
self = this;
this._btn = $('#h-menu-btn').on('click', function() {
self._toggleMenu();
});
},
_toggleMenu: function() {
this._menu = this._menu || $('#h-menu');
this._menu.toggleClass('open');
}
};
We call our little class by instantiating it on page load:
new HorizontalMenu;
Conclusion
Next time you add hidden menus to your web application, why not try the horizontal menu...