Simple jQuery Drop Down Menu

Jquery’s a phenomenal JavaScript library that greatly reduces the amount of JavaScript required for front-end user interface interactions and utility tasks. As a quick introduction to the wonders of jQuery, I’ll demonstrate how simple it is to build a dropdown menu. First off, the HTML:

<div id="page">
<div id="content">
<ul id="menu">
<li><a href="#">About Us</a></li>
<li><a href="#" id="show">Services</a></li>
</ul>
<ul id="service-options">
<li><a href="blinds.html">Products</a></li>
<li><a href="curtains.html">Testimonials</a></li>
<li><a href="interior-designs.html">Contact Us</a></li>
</ul>
<ul id="menu">
<li><a href="#">Products</a></li>
<li><a href="#">Testimonials</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
</div><!--page ends-->

We have a horizontal menu with a fitting ID of ‘menu’, nestled in a ‘content’ DIV. Within the menu there’s a DIV named ‘service-options’ which is a sub menu of ‘services’. Unordered list ‘service-options’ is hidden and only drops down upon clicking the ‘services’ link. Now for the JavaScript:

<script type="text/javascript">
$(document).ready(function() {
// hides the sub menu as soon as the DOM is ready, just before page load)
$('#service-options').hide();
// shows sub menu, service-options, when clicking the 'services' link
$('a#show').click(function() {
$('#service-options').toggle('slow');
return false;
});
});
</script>

Looking at the JavaScript, as soon as the DOM’s ready (once the browser’s reviewed the HTML), the ‘service-options’
ul is hidden using jQuery’s .hide() method. Next, an event handler is assigned to the ‘services’ link which has an ID of ‘#show’. $(‘#service-options’).toggle(‘slow’) attachs the ‘toggle’ method to the sub menu; this toggles it between two states, hidden and not hidden (not hidden being jQuery’s show() method). Incidentally, $(‘#service-options’) is jQuery’s method of selecting an element. That’s it, the event has been assigned to the ‘services’ link ready to toggle the sub menu in and out of view.

Download the file to play around with the script. Of course, you’ll need the jQuery library.

Tags: , , ,

Leave a Reply

*