Ian
Ian

Reputation: 47

hover and slide in jQuery

I'm a beginner at jQuery and I have this little problem. I have this Menu1 that when hovered, displays the SubMenu. My problem is when the SubMenu slides down and I hover it, it slides up back. How do I code it so that when I hover at the SubMenu, it doesnt slide up?

<div id="menu">
    <a href="#" id="items">Menu 1</a>
</div>

<div id="submenu">
    <a href="#">Sub Menu 1</a>
    <a href="#">Sub Menu 2</a>
    <a href="#">Sub Menu 3</a>
</div>

the jQuery:

$(document).ready(function()
    {
        $('#menu').hover(
        function()
        { 
            $('#submenu').slideDown();
        },
        function()
        {
            $('#submenu').slideUp();
        });
    });

Upvotes: 1

Views: 495

Answers (4)

Nabin Kunwar
Nabin Kunwar

Reputation: 1996

Hope it helps

 $(document).ready(function()
    {
    $('#submenu').hide();
    $('#menu').hover(
    function()
    { 
        $('#submenu').slideDown();
    } );
    $('#submenu').mouseout(function(){
         $('#submenu').slideUp();
    });   
    });

Upvotes: 0

sonam
sonam

Reputation: 3760

Here's your problem. when you hover in sub menu, this action resembles hover out event on menu 1 , so submenu slides up. so to prevent this what you could do is place the submenu div inside menu div as below:

<div id="menu">
    <a href="#" id="items">Menu 1</a>
    <div id="submenu">
       <a href="#">Sub Menu 1</a>
       <a href="#">Sub Menu 2</a>
       <a href="#">Sub Menu 3</a>
    </div>
</div>

Also hide the submenu at first as below:

 $('#submenu').hide();
 $('#menu').hover(
    function () {
       $('#submenu').slideDown();
    },
    function () {
      $('#submenu').slideUp();
    }
 );

Working demo : http://jsfiddle.net/YUhWd/

Upvotes: 0

Satinder singh
Satinder singh

Reputation: 10198

HTML- Add extra wrapper div

   <div id="holderDiv">
    <div id="menu">
        <a href="#" id="items">Menu 1</a>
    </div>
   <div id="submenu">
        <a href="#">Sub Menu 1</a>
        <a href="#">Sub Menu 2</a>
        <a href="#">Sub Menu 3</a>
    </div>
    </div>

JQuery-

$("#submenu").hide();
   $("#menu").on('mouseover', function () {
         $("#submenu").slideDown(500);
   });

    $("#holderDiv").on('mouseleave', function () {
           $("#submenu").slideUp(500);
    });

DEMO

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can change your HTML markup and nest the HTML submenu inside the menu, tahn use slideToggle in your hover function

HTML:

<div id="menu"> 
    <a href="#" id="items">Menu 1</a>
    <div id="submenu" style="display: none"> 
        <a href="#">Sub Menu 1</a>
        <a href="#">Sub Menu 2</a>
        <a href="#">Sub Menu 3</a>
    </div>
</div>

JS:

$(document).ready(function () {
    $('#menu').hover(function () {
        $('#submenu').slideToggle();
    });
});

Demo: http://jsfiddle.net/DH5Lw/

Upvotes: 2

Related Questions