0

So I am trying to create a drop down menu using .hover() and .toggle(). While Have managed to get the menu to appear when the user rolls over the link, it disappears when the user moves off the link to select an item from the menu. Is there a method or technique for keeping the menu toggled even when the user isn't still hovering over the link?

Here is the JS:

<script type="text/javascript">
$(document).ready(function() {
$("#menu_link").hover(function () {
$("#the_menu").toggle();
});
});
</script>
0

2 Answers 2

3

Put the menu element inside the link.

Sign up to request clarification or add additional context in comments.

2 Comments

I thought about that but it seemed like that might interfere with the anchor tags inside the menu element. No?
@Thomas: This is usually done by making each menu item an <li>, and making the submenus <ul> elements inside the <li>. You can also put an <a> inside the <li>.
1

The solution can vary greatly depending on the HTML markup you're using. But a general solution to these kinds of things is to let the body element detect "mouseenters" and detect which element the event originated from. If it's not either #menu_link or #the_menu, then hide the menu.

$("body").mouseenter(function (e) {
   var eventParents = $(e.target()).parents();
   if (eventParents.index($("#menu_link")) == -1 &&
         eventParents.index($("#the_menu")) == -1) {
      $("#the_menu").hide();
   }
});

$("#menu_link").mouseenter(function () {
   $("#the_menu").show();
});

This gives you flexibility in, for example, placing the menu link in a different container div to the menu itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.