April 17, 2012

Drop Down menu in Jquery

Question by Kamal

hello friends i have tryied folowing code as u can see here http://jsfiddle.net/QCdz4/ i want to code for drop down menu to appear on click() and disappear when mouseout() but its not working please help me out Thank in advance

Jquery

<script>
    $(document).ready(function(){
        $('.click ul').css({display:'none', position:'absolute'});
        $('.click').click(function() {
            $(this).children('ul').slideDown(200);
            $(this).on('mouseout', function() {
                $(this).children('ul').slideUp(200);
            })
        })
    })
</script>

HTML

<div class="click">
    click
    <ul>
        <li><a href="#">one</a></li>
        <li><a href="#">two</a></li>
        <li><a href="#">three</a></li>
        <li><a href="#">four</a></li>
    </ul>
</div>

Answer by ThdK

You need mouseleave instead of mouseout because mouseout will also be triggered when you hover from the parent to a child element. The child element positioned above (read: z-index) the parent. Moving the cursor in this case from parent to child element will trigger the mouseout event but not the mouseleave event. The mouseleave element will only be triggered when you move the cursor away from the parent AND it’s children.

$(document).ready(function(){

   $('.click ul').css({display:'none', position:'absolute'});


   $('.click').on('click', function(){
       $("ul", $(this)).slideDown(200);
   }).on('mouseleave', function(){
       $("ul", $(this)).slideUp(200);
   });   


})

Update: A very good article with a very clear live demo can be found here: Different between mouseout and mouseleave in jquery.
(Check out the the square’s with child elements. The one on the bottom right)

Answer by Starx

You are chaining your function the wrong way.

$('.click').click(function(){
     $(this).children('ul').slideDown(200);
}).on('mouseout', function(){
    $(this).children('ul').slideUp(200);
});

Improving the above code,

$('.click').on('click', function(){
     $("ul", $(this)).slideDown(200);
}).on('mouseout', function(){
    $("ul", $(this)).slideUp(200);
});

Update

To ensure a event triggers once the cursor is outside the element, you have to use mouseleave instead of mouse out

$('.click').on('click', function(){
     $("ul", $(this)).slideDown(200);
}).on('mouseleave', function(e){
        $("ul", $(this)).slideUp(200);
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!