Matt
Matt

Reputation: 828

jquery hover menu fadein/hide dropdown

I have a little jquery

    $(".dropdown").hide();

$('#mainnav ul li').hover(function(e){
        $(this).children('.dropdown').fadeIn(250);
}, function(e) {
        $(this).children('.dropdown').hide();
});

This fades in and hides each menu drop down when it's parent LI is hovered over.

I'm not convinced this is jquery is robust enough. Sometimes the dropdowns don't hide if the mouse is moved accross the parent li's at speed.

Is there anything I can do to improve the reliability of this code?

Thanks

Upvotes: 0

Views: 1871

Answers (2)

Stichoza
Stichoza

Reputation: 4609

as xFortyFourx mentioned, you can use .stop() method to clear the queue. As jQuery documentation says, stop method works only with animations, so you'd better use .animate() instead of .fadeIn() and .fadeOut()

$("#mainnav ul li").hover(
    function() {
         $(this).children('.dropdown').stop().animate({opacity: 1});
    },
    function() {
        $(this).children('.dropdown').stop().animate({opacity: 0});
    }
);

using .stop() with .fadeIn() will cause freezing elements at semi-transparent mode. See live preview of both situations here: http://jsfiddle.net/stichoza/faqNt/

Upvotes: 1

Michael Antonius
Michael Antonius

Reputation: 972

maybe this code can help you :

    $(".dropdown").hide();
    $('#mainnav ul li').hover(function(){
        $(this).children('.dropdown').stop().fadeIn(250);
     }, function() {
        $(this).children('.dropdown').stop().hide();
    });

or

$('#mainnav ul li').hover(function(){
  if($(this).children('.dropdown').css('display') == 'none'){
     $(this).children('.dropdown').fadeIn(250);
  } else {
     $(this).children('.dropdown').stop().hide();
  }
});

Good luck

Upvotes: 0

Related Questions