Using jQuery for DHTML Drop-Down Menus
You may have heard of the Suckerfish Dropdowns featured on A List Apart (which use CSS and JavaScript along with valid HTML to create vertical or horizontal “drop-down” menus) and the the extended revised version Son of Suckerfish, but if you’re already using the jQuery library on your site the code to mimic the :hover pseudo-class gets even simpler.
Instead of:
1 2 3 4 5 6 7 8 9 10 11 12 13 | sfHover = function() { var sfEls = document.getElementById("nav").getElementsByTagName("LI"); for (var i=0; i<sfels .length; i++)="" {=""> sfEls[i].onmouseover=function() { this.className+=" sfhover"; } sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); } } } if (window.attachEvent) window.attachEvent("onload", sfHover); </sfels> |
You only need:
1 2 3 4 5 | jQuery('#nav li').hover(function(){ $(this).addClass('sfhover'); //mouseover }, function(){ $(this).removeClass('sfhover'); //mouseout }); |
Such is the beauty of using css-style selectors to build an array of affected elements. Of course, you must make sure the code is wrapped in $(document).ready(function(){…});, but there is no need to modify the window.onload event in this example. Otherwise, refer to the code provided in the above examples to get your markup and formatting styles in place.
