Search code examples
javascriptjquerytoggleslide

JQuery Toggle Slide – display element when other elements toggle closed


JSFiddle: http://jsfiddle.net/ncuacvcu/

DIV home is displayed by default.

When I click on LINK one/LINK two, DIV one/DIV two replaces DIV home. When I click on LINK one/LINK two again, DIV one/DIV two toggles shut, leaving an empty white space. How do I get DIV home to display again at that moment?

At the same time, if DIV one is open and I click on LINK two, I want DIV one to be replaced by DIV two (i.e. without going through DIV home).

Here's what I tried (and some variations), but I can't get it to work:

 $("a#one_toggle").click(function()
         {
           $(".hideall").not(".one").slideUp();
           $(".one")slideToggle(function(){
               if($('#client1').is(':visible')){
                   $('#client0').SlideUp();
               } else{
                   $('#client0').SlideDown();
               }
         });
 });

Thanks in advance for any tips!


Solution

  • You need to use the callback of slideToggle and check if the div with class home is visible or not then you show it.

    http://api.jquery.com/slidetoggle/

    http://api.jquery.com/is/

    $(function() {
        $("a#one_toggle").click(function() {
             $(".hideall").not(".one").slideUp();
             $(".one").slideToggle('slow', function() {
                showHome($('.one'));
             }); 
        });
               
        $("a#two_toggle").click(function() {
             $(".hideall").not(".two").slideUp();
             $(".two").slideToggle('slow', function() {
                showHome($('.two'));
             }); 
        });
    });
    
    function showHome(elementToCheck) {
        // now we know if the div to check is visible or not
        if (!$(elementToCheck).is(':visible')) {
            // the div is not visible so we show it
            $('.home').slideDown();
        }
    }
    .one,
    .two {
      display:none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" id="one_toggle">link one</a>
    <a href="#" id="two_toggle">link two</a>
    
    <div class="home hideall">
      home
    </div>
    
    <div class="one hideall">
      one
    </div>
    
    <div class="two hideall">
      two
    </div>