Convert a Menu to a Dropdown for Small Screens

<!DOCTYPE html>
<html>
<head>
<meta charset=’UTF-8′>
<title>Convert Menu to Dropdown</title>
<style>
* {
margin: 0;
padding: 0;
}
h1 {
font: 300 21px “HelveticaNeue-Light”, “Helvetica Neue Light”, “Helvetica Neue”, Helvetica, Arial, “Lucida Grande”, sans-serif;
width: 500px;
margin: 0 auto 15px;
}
nav {
display: block;
width: 960px;
margin: 100px auto;
text-align: center;
}
nav ul {
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: inline-block;
background: #333;
color: white;
padding: 5px 15px;
border: 1px solid white;
text-decoration: none;
}
nav a:hover {
border: 1px solid red;
background: red;
}
nav a:active {
background: blue;
}
nav select {
display: none;
}
@media (max-width: 960px) {
nav ul {
display: none;
}
nav select {
display: inline-block;
background:#FFFFFF;
color:#7C7C7C;
padding:5px;
width:175px;
border:solid 1px #7C7C7C;
}
}
</style>
<!– You COULD just put both menus in the markup,
but if you don’t like that, this is how you
could dynamically create it with jQuery. –>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js”></script>
<script>
// DOM ready
$(function() {

// Create the dropdown base
$(“<select />”).appendTo(“nav”);

// Create default option “Go to…”
$(“<option />”, {
“selected”: “selected”,
“value” : “”,
“text” : “Select a Page”
}).appendTo(“nav select”);

// Populate dropdown with menu items
$(“nav a”).each(function() {
var el = $(this);
$(“<option />”, {
“value” : el.attr(“href”),
“text” : el.text()
}).appendTo(“nav select”);
});

// To make dropdown actually work
$(“nav select”).change(function() {
window.location = $(this).find(“option:selected”).val();
});

});
</script>
</head>
<body>
<nav>
<h1>This menu turns into a &lt;select&gt; when window is less than 960px to conserve space.</h1>
<ul>
<li><a href=”#” class=”active”>Home</a></li>
<li><a href=”#books”>Books</a></li>
<li><a href=”#blog”>Blog</a></li>
<li><a href=”#about”>About Us</a></li>
<li><a href=”#support”>Support</a></li>
</ul>
</nav>
</body>
</html>

Leave a Reply