Search code examples
javascriptjqueryhtmlminimize

Minimize and Maximum one Div when many are displayed


I made an update to someone's coding at How to maximize and minimize a div.

I wanted to see if I can populate various listings below each other and depending on which one selected, it will maximize or minimize.

However, when testing this, only the first one will work. Any reason this is so?

https://jsfiddle.net/Qy6Sj/1887/

Coding:

$("#max_min_button").click(function(){
if($(this).html() == "-"){
    $(this).html("+");
}
else{
    $(this).html("-");
}
$("#news_body").slideToggle();
});

I have tested some of the coding found at minimize maximize the div ? javascript or jquery which works for all the div but it wasn't working.

I tried this code example at http://wpapi.com/minimize-restore-maximize-hide-functionality-javascript-jquery/ but it didn't work either.


Solution

  • I have restructured your html & css slightly and rewritten the jQuery/JS to find the next news_body and toggle it.

    HTML:

    <div class="weekly-news">
        <div class="title_bar">Energy Group guidelines
            <div class="max_min_button">-</div>
        </div>
        <div class="news_body">Hi welcome!</div>
    </div>
    <div class="weekly-news">
        <div class="title_bar">Energy Group brand
            <div class="max_min_button">-</div>
        </div>
        <div class="news_body">Hi welcome!</div>
    </div>
    

    CSS:

    .weekly-news{
        width:600px;
        border:solid 1px;
    }
    
    .title_bar{
        background: #FEFEFE;
        height: 25px;
        width: 100%;
    }
    .max_min_button{
        border:solid 1px;
        width: 25px;
        height: 23px;
        float:right;
        cursor:pointer;
    }
    .news_body{
        height: 250px;
        background: #DFDFDF;
    }
    

    JS:

    $(".max_min_button").click(function(){
        if($(this).html() == "-"){
            $(this).html("+");
        }
        else{
            $(this).html("-");
        }
        var thisParent = $(this).parent();
        $(thisParent).next(".news_body").slideToggle();
    });
    

    DEMO: JSFiddle