I have an expandable vertical drop down menu that currently expands when first level items are clicked, however I want it to expand when the menu item is hovered over instead. The original script is:
<script type="text/javascript">
$(document).ready(function () {
$('#nav > li > a').click(function(){
if ($(this).attr('class') != 'active'){
$('#nav li ul').slideUp();
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
}
});
});
</script>
I changed .click(function to .hover(function and this works, however I don’t know if it is the best way to do it. Can anyone advise if there is a better way to acheive this? You can see a working example of the .click version of the menu on the left hand side of the page by clicking here. Thanks!
Changing it to hover is acceptable. It’s definitely very readable code, which is the important thing. However, there is one issue – as Daniel comments, it’ll make your menu impossible to navigate on a touch device, which means that you’re making the site inaccessible on every mobile phone and tablet*. This is a very bad thing, but there are a few things you can do.
For instance, the jQTouch library has some awesome touch-specific event handling that would let you optimize your menu for mobile users. Otherwise, you could wrap your menu’s JavaScript logic in a conditional, or you could assign each action to both touch and click.
*except for phones and tablets with mice (a very atypical use case.)