Search code examples
javascriptjqueryslidedownslideup

Jquery slide down only if not already visible


I have a simple problem using Jquery. I want to display detailed information under menu headings, but the interface isn't so smooth. After a few hours of trying some things out, I've come back to the beginning to see if there is a simple answer

Look at this example

Two problems:

  1. If you mouse over several categories at once to get to the category you want, the animation still runs through all of the other animations instead of stopping the other ones and only animating the one that the mouse is currently hovered over.

  2. If you mouse over a category that is already open, it still runs the animation, but I only want the animation to run if the content is not already visible. Is there a simple if statement that can do this?


Solution

  • $('.content').hide();
    var $elms = $('.fruit, .vegetable, .dairy');
    $elms.hover(function() {
        var $content = $(this).next('.content');
        $content.stop(1, 1).slideToggle(400);
    });
    

    http://jsfiddle.net/elclanrs/GBkMB/1/

    Edit:

    To prevent the content from sliding back up you can nest the divs like so:

    <div class="fruit">fruit
        <div class="content fruit_types">apple<br/>bannana<br/>orange</div>
    </div>
    <div class="vegetable">vegetable
        <div class="content vegetable_types">celery<br/>lettuce<br/>cucumber</div>
    </div>
    <div class="dairy">dairy
        <div class="content dairy_types">milk<br/>cheese<br/>butter</div>
    </div>
    

    jQ:

    $('.content').hide();
    var $elms = $('.fruit, .vegetable, .dairy');
    $elms.hover(function() {
        var $content = $(this).children('.content'); //<-`children()` not `next()`
            $content.stop(1,1).slideToggle(400);
    
    });
    

    Example: http://jsfiddle.net/elclanrs/GBkMB/5/