Ad

Unfold Submenu Conditions (jQuery)

- 1 answer

I'm stuck with a jQuery issue that I don't manage to solve. I've created a menu with sub menu elements. I would like to toggle the height of content by clicking in menu items. The thing is when I click on other item, the content collapse. Kind of tricky to explain, I've put two websites doing the job http://www.polerstuff.com/ -> When you click on 'shop' and then on 'info', the sub menu stays open. The same trick was seen here http://topodesigns.com/

I guess these two websites are using Shopify.

$(document).ready(function() {
    $(".button").on("click", function() {
        if($(".content").height() == 0) {
            $(".content").animate({height: "300px"});
        }
        else if($(".content").height() == 300) {
            $(".content").animate({height: "0px"});
        }
     });
});

Here is my jsfiddle -> Thank a lot in advance.

Ad

Answer

Here's version of your fiddle that uses the data attribute to target divs with desired content, and another data tag containing desired heights to animate (but there are many other ways). Clicking on the same button toggles it shut, this is achieved by adding an indicative class. The 'hiding' divs may contain further divs with classes and layout as required.

$(document).ready(function (){
    $(".b").on("click", function (){ 
    
      var $this = $(this),
    	  target = $this.data('target'),
          tall = $this.data('tall'),
          content = $(".content");
          
        target = $('.'+target).html(); // get the html content of target divs
        content.html(target); // insert said content
          
      	if (!$this.hasClass('on')) {   // if it hasn't been clicked yet..
           $(".b").removeClass('on');  // say that none have been clicked
		   $this.addClass('on');     // say that just this one has been clicked
           content.animate({height: tall}, 200); // animate to the height specified in this buttons data attribute
        } else {
           content.animate({height: "0px"});
		   $this.removeClass('on');  
        }
    });
});
.content {
    background: coral;
    width: 100%;
    height: 0px;
    overflow:hidden;  
}

.hiding{
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<butippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<button class="b" data-target="alpha" data-tall="4em">Button</button>
<button class="b" data-target="bravo" data-tall="7em">Button</button>
<button class="b" data-target="charlie" data-tall="5em">Button</button>

<div class="content">Le contenu</div>

<div class="hiding alpha"> some stuff </div>
<div class="hiding bravo"> other things </div>
<div class="hiding charlie"> bits and pieces </div>

Ad
source: stackoverflow.com
Ad