jquery.cmenu.js
A simple, accessible, configurable way to support collapsing horizontal navigation menus on your site. You can check it out on the left hand side of this page.
The main features are:
- Dual licenced under GPL / MIT licences - do what you want with this code (as long as you leave the licence intact!)
- Lightweight (~2Kb packed)
- Keyboard accessible, basic WAI-ARIA support. Usable with JavaScript switched off.
- Easy to use and deploy
- Configurable through CSS, callback functions and numerous options
Usage
Your HTML should be in the following form:
<ul id="mainNav">
<li><a href="#">Menu Item 1</a>
<ul>
<li><a href="#">Submenu Item 1</a></li>
<li><a href="#">Submenu Item 2</a></li>
<li><a href="#">Submenu Item 3</a></li>
</ul>
</li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a>
<ul>
<li><a href="#">Submenu Item 1</a></li>
<li><a href="#">Submenu Item 2</a></li>
<li><a href="#">Submenu Item 3</a></li>
</ul>
</li>
</ul>
Include the javascript as follows. Please refer to your local copy of jQuery (Or the hosted CDN version.)
You only need to include the jquery.cookie.js plugin if you want open menus to be remembered between page loads.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script src="jquery.cookie.js"></script> <script src="jquery.cmenu.js"></script>
Finally, call the plugin on the parent list:
<script>
$(function(){
$('#mainNav').cmenu();
});
</script>
Options
- animationIn
- animationOut
This should be a JavaScript object as passed to $.animate(). For example {height: 'show'}, {height:'hide'}, or {opacity: 'show'}
- animationInSpeed
- animationOutSpeed
Can be either a string (slow, medium, or fast) or an integer (ms).
- remember
If this option is set to true, and jquery.cookie.js has been included, the menus that are open will be remembered between page refreshes.
- init
- onBeforeIn
- onIn
- onBeforeOut
- onOut
These are callback functions that are invoked at various points. init() is called when the plugin loads; onBeforeIn() is called before a submenu is shown; and onIn() is called immediately after a submenu is shown. Similarly, onBeforeOut is called just before a submenu is hidden, and onOut immediately after it is hidden.
Using options
Change the way the plugin works by implementing options in the following way:
<script>
$(function(){
$('#mainNav').cmenu({
animationIn: {opacity: 'show'},
animationOut: {opacity: 'hide'},
animationInSpeed: 500,
animationOutSpeed: 'slow',
remember: true,
init: function(){
alert('cMenu has loaded!');
},
onIn: function(){
alert('A submenu has just been shown!');
}
});
});
</script>