Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

How to delay mousover part of hover() function in jquery and to be only executed when cursor is on the element for some given duration

<ul id="menu">
<li>What's new?
    <ul class="active">
        <li><a href="#">Weekly specials</a></li>
        <li><a href="#">Last night's pics!</a></li>
        <li><a href="#">Users' comments</a></li>
    </ul>
</li>
<li>Member extras
    <ul>
        <li><a href="#">Premium Celebrities</a></li>
        <li><a href="#">24-hour Surveillance</a></li>
    </ul>
</li>
<li>About Us
    <ul>
        <li><a href="#">Privacy Statement</a></li>
        <li><a href="#">Terms and Conditions</a></li>
        <li><a href="#">Contact Us</a></li>
    </ul>
</li>
</ul>

Jquery code:

 <script>
    $(document).ready(function(){

        $('#menu>li>ul>li').hide();

        $('#menu>li').click(function(e){e.stopPropagation();});



        $('#menu>li').hover(

                function(){

                    t=$(this);

                    $(t).find('ul>li').slideToggle();
                },

                function(){

                    $(t).find('ul>li').slideToggle();
                }
        );

    });

</script>

i want to make a vertical menu list with sub lists which expands when mouse is hovered on it and collapse when mouse is out . The above mention code works well but the only thing is while moving the cursor from downwards to upwards across the list every item till i reach top of the list expands and collapse.What should i include to avoid this behavior so that list item will expand only when cursor is resting on it for some duration(say 500 milisecs)

Upvotes: 4

Views: 696

Answers (3)

Evan Davis
Evan Davis

Reputation: 36592

Adding this as an answer since it seemed to solve your problem:

There is a wicked library called Hover Intent to do just the thing. It overrides the standard .hover() method with a configurable delay.

Upvotes: 1

SarathSprakash
SarathSprakash

Reputation: 4624

DEMO

Try this

$(document).ready(function () {

    $('#menu>li>ul>li').hide();

    $('#menu>li').click(function (e) {
        e.stopPropagation();
    });



    $('#menu>li').hover(

    function (event) {
        event.preventDefault();
        $(this).find('ul>li').stop().slideDown();
    },

    function (event) {
        event.preventDefault();
        $(this).find('ul>li').stop().slideUp();
    });

});

Hope this helps,thank you

Upvotes: 0

You will need a setTimeout:

$('#menu>li').hover(
    function(){
        var t = $(this);

        setTimeout(function(){
            if(t.is(":hover")) // Don't fire the event if #menu>li is not hovered
                t.find('ul>li').slideToggle();
        }, 500);
    },
    function(){
        $(this).find('ul>li').slideToggle();
    }
);

Upvotes: 1

Related Questions