I have a dropdown menu that is displayed when the user hovers over a nav link. This is being triggered in jQuery with .hover(). The opening and closing of this dropdown works fine on touch devices when the user clicks the nav link (iPad/iPhone), but I am trying to hide the dropdown when the user clicks anywhere else on the page.
Here is a link to my JSFiddle with a basic setup.
I have found ways of doing this with .click(), but not .hover().
This is my basic jQuery code:
$('.hoverItem').hover(function(e) {
$('.dropdown').toggleClass('visible');
e.stopPropagation()
});
Why not make the body clickable, and hide the dropdown when it is clicked like this?
HTML:
<body id="clickArea">
<div class="hoverItem">Hover here to show dropdown</div>
<div class="dropdown">Dropdown Area</div>
</body>
JS:
$('.hoverItem').hover(function(e) {
$('.dropdown').toggleClass('visible');
});
$('#clickArea').click(function(e) {
$('.dropdown').toggleClass('visible');
});
First, it is far better, imho, to use:
.on(click, function(e))
vs
.hover(function(e))
Next, would be an if / else statement.
var navcheck = $(this).attr(class);
if(navcheck!=dropdown){ $(.dropdown).hide(); } else { $(dropdown).show(); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.