inaz inaz - 3 months ago 11
CSS Question

how to change the div height property to auto when I click on '"more" button

there is a list of elements and i need to expand each element on click the more button and collapse each element when click on the less button. but when i click to more button all div will open at the same time also i can't close them . click on the less button.
here is the code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.hidi{
height:20px;
overflow:hidden;
border:1px solid red;

}
</style>
</head>
<body>
<div class="hidi">
<div class="uner-sch">
1
</div>
<div class="uner-sch">
2
</div>
<div class="uner-sch">
3
</div>
</div>
<div class="more"> ... More +</div>

<div class="hidi">
<div class="uner-sch">
1
</div>
<div class="uner-sch">
2
</div>
<div class="uner-sch">
3
</div>
</div>
<div class="more"> ... More +</div>

<script>
$(".more").click(function(){
var el = $('.hidi'),
curHeight = el.height(),
autoHeight = el.css('height', 'auto').height();
el.height(curHeight).animate({height: autoHeight}, 1000),
$(this).text('... less -');


});
</script>
</body>
</html>

Answer

Try this:

HTML:

<div class="container">
    <div class="hidi">
        <div class="uner-sch">
        1
        </div>
        <div class="uner-sch">
         2
        </div>
        <div class="uner-sch">
        3
        </div>
    </div>
    <div class="more"> ... More +</div>
</div>

<div class="container">
    <div class="hidi">
        <div class="uner-sch">
        1
        </div>
        <div class="uner-sch">
         2
        </div>
        <div class="uner-sch">
        3
        </div>
    </div>
    <div class="more"> ... More +</div>
</div>

jQuery:

var curHeight = $('.hidi').height();
$(".more").click(function(){
    var container = $(this).parent('.container');
    var el = container.find('.hidi');
    var autoHeight = el.css('height', 'auto').height();
    if(el.hasClass('open')){
        el.removeClass('open');
        el.height(autoHeight).animate({height: curHeight}, 1000), $(this).text('... less -');
    }
    else{
        el.addClass('open');
        el.height(curHeight).animate({height: autoHeight}, 1000), $(this).text('... more +');
    }
});

Working example: https://jsfiddle.net/hwunuz7b/

Comments