Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show/hide dropdown menu on hover/mouseout using jquery

Tags:

jquery

so i have a simple navbar with a dropdown menu for when a user hovers on the more tab. i want to hide the dropdown menu when the user mouses out of the categories div.

problem is that when the user mouses into a ul li, the dropdown closes. how can i set it so that the function ignores the ul li within the categories div. tried categories > * but didn't work.

<div id="navbar">
  <ul>
    <li>tab1</li>
    <li>tab2</li>
    <li id="moretab">more</li>
  </ul>
</div> 
<div id="categories">
  <ul>
    <li>cats</li>
    <li>dogs</li>
  </ul>
</div>

$("#moretab").hover(function(){
  $("#categories").css("visibility","visible"); 
});
$("#categories").mouseout(function() {
    $("#categories").css("visibility","hidden"); 
});
like image 503
Jung Avatar asked Jun 12 '09 21:06

Jung


People also ask

How to show drop down list on hover?

Example ExplainedUse any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.

How to hide dropdown menu CSS?

Answer: Use the CSS :hover pseudo-class If you simply want to show and hide dropdown menu on mouse hover you don't need any JavaScript. You can do this simply using the CSS display property and :hover pseudo-class.

How to hide dropdown list in html?

We use <select> and <option> elements to create a drop-down list and use disabled attribute in <select> element to disable the drop-down list element.

Which CSS property is used to show dropdown items?

The :hover selector is used to show the dropdown menu when the user moves the mouse over the dropdown button.


3 Answers

$(document).ready(function () {

  $("#moretab").mouseenter(function(){
    $("#categories").show(); 
  });

  $("#categories, #moretab").mouseleave(function(){
    $("#categories").hide(); 
  });
});
like image 102
Sveisvei Avatar answered Oct 11 '22 15:10

Sveisvei


The easiest answer is how you would do it without jQuery: put the dropdown in the triggering element (e.g. dropdown list in a list item in the navigation list).

If you want something less straightforward, mouseleave might help.

like image 34
Alan Plum Avatar answered Oct 11 '22 15:10

Alan Plum


Jquery hover plugin includes both mouseenter and mouseleave function and following code works fine for me.

javascript:

$(document).ready(function(){
    $('.dropdown').hover(
    function(){
        $(this).children('.sub-menu').slideDown('fast');
    },
    function () {
        $(this).children('.sub-menu').slideUp('fast');
    });
});
like image 42
veeresh yh Avatar answered Oct 11 '22 15:10

veeresh yh