I’ve got a simple jquery menu set up… it works fine except for the parent item. I’ve only listed one parent item, but there may be many, so raw #id won’t work for this either. I want to apply a class when it is CLICKED, but then remove that class when the user hovers elsewhere and the menu slides away.
Here is what I have so far that isn’t working for me.
<script type="text/javascript">
$(document).ready(function () {
$("ul.topnav li a").click(function () {
$(this).parent().find("ul.subnav").slideDown('fast').show();
$(this).parent().hover(function () {
}, function () {
$(this).parent().find("ul.subnav").slideUp('slow');
$(this).parent().removeClass("subhover");
});
}).before(function () {
$(this).addClass("subhover");
});
});
<ul class="topnav">
<li><a href="#">Item 1</a></li>
<li class="dropdownmenu">
<a href="#">Menu Parent</a>
<ul class="subnav">
<li>Item</li>
</ul>
</li>
</ul>
I’m not really sure what you’re trying to do with
.before, but either way, it’s not being used the right way. It’s meant to insert elements before the selected one, and as far as I know, doesn’t take a function.It’s also not a good idea to bind events inside other event’s functions unless you unbind them later. This could potentially cause issues if the user were to click multiple times. You can also use the
mouseleavemethod rather than one empty hover function.This will bind the click event to the
anchor, and bind the mouseleave function to the parentli.