Search code examples
jquerytogglehideshowtoggleclass

jQuery hide and show toggle keeping active only one div


I am a starter with JQuery, and Javascript, and I would like to know how should I edit the following code so that when I click on a heading, the content under the other headings, will be hidden? I also want the arrows to function properly.

Basically, I want to keep only one content active when clicking on a heading?

Here is the code I have: http://jsfiddle.net/mL79571z/1/

$(".prod_options").hide();
$(".stag_options").hide();
$(".qa_options").hide();

$("#show_prod_options").click(function(){
    $(".prod_options").slideToggle("slow");
    $("#arrow_prod").toggleClass("glyphicon-chevron-down glyphicon-chevron-up");
});
$("#show_stag_options").click(function(){
    $(".stag_options").slideToggle("slow");
    $("#arrow_stag").toggleClass("glyphicon-chevron-down glyphicon-chevron-up");
});
$("#show_qa_options").click(function(){
    $(".qa_options").slideToggle("slow");
    $("#arrow_qa").toggleClass("glyphicon-chevron-down glyphicon-chevron-up");
});

Thanks!


Solution

  • http://jsfiddle.net/mL79571z/13/

    HTML (repeat for each option you require):

    <div class="env_menu_options dropMenu" id="stag_env_menu_options">
        <div class="env_list" id="show_stag_options">
            <span id="arrow_stag" class="glyphicon glyphicon-chevron-down arrow"></span> Heading 2
        </div>
        <div class="stag_options detail">Content 2 <br>Content 2</div>
    </div>
    

    CSS:

    .detail {
        display:none;   
    }
    

    JS:

    $(".dropMenu").on("click", function () {
        var notThisOne = $(this);
    
        $(".dropMenu").each(function() {
            if ($(this).attr("id") !== notThisOne.attr("id")) {            
                $(this).find(".arrow").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
                $(this).find(".detail").slideUp("slow");
            } 
            else {
                $(this).find(".arrow").toggleClass("glyphicon-chevron-down glyphicon-chevron-up");
                $(this).find(".detail").slideToggle("slow");                
            }        
        });    
    });