stack
stack

Reputation: 10218

How can I set element's height the same as its content?

Here is my code:

$("#topbar").click(function () {
    $(this).animate({
        height: ($(this).height() == 45) ? 20 : 45
    }, 200);
});
#topbar {
    background: orange;
    color: white;
    display:block;
    width:100%;
    text-align:center;
    height:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='topbar'>
toggle me
<br>
some explanations
<br>
some more explanation

</div>

As you see, when you click on the orange box, its height will be increased (and vice versa). But 45 isn't an enough height for current content. Actually the content of that box is dynamic. So I want to set a height the same as its content's height.

How can I do that?

Upvotes: 0

Views: 56

Answers (2)

Sahil Dhir
Sahil Dhir

Reputation: 4250

Here is the solution. Credit goes to Jai.

$("#topbar").click(function() {
  $(this).animate({
    height: ($(this).height() == 20) ? this.scrollHeight : 20
  }, 200);

});
#topbar {
  background: orange;
  color: white;
  display: block;
  width: 100%;
  text-align: center;
  height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='topbar'>
  toggle me
  <br> some explanations
  <br> some more explanation
  <br> some more explanation
  <br> some more explanation
  <br> some more explanation<br> some more explanation

</div>

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You are using condition if height is 45 or not and then assign 20 for true and 45 for false condition. Instead, follow below code -

var collapse = false;
$("#topbar").click(function () {
    var ht = (collapse? 20 : this.scrollHeight);
    collapse=!collapse;
    $(this).animate({
        height: ht
    },200);
    
});
#topbar {
    background: orange;
    color: white;
    display:block;
    width:100%;
    text-align:center;
    height:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='topbar'>
toggle me
<br>
some explanations
<br>
some more explanation

</div>

Upvotes: 3

Related Questions