I have a pretty simple jQuery dropdown menu with links in the usual ul/li list arrangement. The code for the dropdown is as follows:
$('body').ready(function() {
if(screen.width <= 720) {
$('.dropdown').hover(function() { $(this).find('.subMenu').toggle(); });
$('.dropdown').click(function() { if( $('this').css('display') != 'none') {
$('this').toggle();
}
});
}
else
{
$('.dropdown').hover(
function() { $(this).stop(true,true).find('.subMenu').slideDown("fast"); },
function() { $(this).stop(true,true).find('.subMenu').hide(); }
);
}
});
On mobile devices (ignore the 720 width, it's just for testing right now), I would like to achieve the following functionality:
User taps link with a dropdown menu > If menu is open, close it
User taps link while another menu is already open > Close previous menu, open current menu
- User taps somewhere else on the page > Close any open menus
I found that the hover function actually handles #2 and #3, but I can't figure out how to get #1 working. I'm fairly certain that I know why this particular attempt
$('.dropdown').click(function() { if( $('this').css('display') != 'none') {
$('this').toggle();
}
});
fails. I'm guessing that the click (or tap, in this case) triggers the hover event, which seems to take precedence and therefore displays the menu, instead of hiding it.
How can I get this working on mobile devices?
Edit: I'm using jQuery v1.7.2
HTML list structure is as follows, in case it helps someone (abridged version):
<div id="navbar">
<ul>
<li class="dropdown"><a href="#">Link A</a></li>
<li class="dropdown"><a href="#">Link B</a>
<ul class="subMenu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
</ul>
</div>