Miraj
Miraj

Reputation: 59

Toggle height of a div with jquery

I have a div with the class name 'content' and it has some content. I have set its height to 80px. height:80px; overflow:hidden;

I have a button with class name 'button' and I am trying to toggle and make the height auto or remove the height 80 px on click and then once clicked again take the div back to 80px.

I am also trying to have the button change its value in-between show more/show less

Thanks

Upvotes: 0

Views: 4574

Answers (4)

David
David

Reputation: 393

Check this code snippet. Hope it helps!

$(".btn").on("click", function(){
	var $btn = $(".btn");
  var $content = $(".content");
  $content.toggleClass("sized");

  if($btn.text() == "Show More"){
  	$btn.text("Show Less")
  } else if($btn.text() == "Show Less"){
  	$btn.text("Show More")
  }
});
body{
  font-family: sans-serif;
}
.content{
  height: 80px;
  background: #f3f3f3;
  padding: 5px 10px;
  box-sizing: border-box;
  border-radius: 3px;
}
.btn{
  margin-top: 10px;
  padding: 10px;
  background: #d63333;
  display: inline-block;
  color: #fff;
  border-radius: 3px;
  cursor: pointer;
}
.sized{
  height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content sized">Hello World!</div>
<div class="btn">Show More</div>

Upvotes: 1

Syed Muhammad Asad
Syed Muhammad Asad

Reputation: 228

Here is a solution for to get rid to much javascript,

$('.button').click(function(){
  $('.content').toggleClass('changeHeight');
  $('.button > *').toggleClass('show hide')
})
.show {display: block;}
.hide {display: none;}
.content {height: 80px; background: red; color: white;}
.content.changeHeight {height: auto;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="content">
  <div>Some contents</div>
</div>
<button class="button">
  <span class="show">Show</span>
  <span class="hide">Hide</span>
</button>

If you want to animate it, you can add transition to class content.

Also there is another useful way to toggle class to parent element containing both these elements (button and div).

Upvotes: 1

Moneer Kamal
Moneer Kamal

Reputation: 1877

here is something that may help you

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

Upvotes: 0

Frodi Gest
Frodi Gest

Reputation: 33

.height {
    height: 80px;
}

$(".button").click(function(){
    $("div.container").toggleClass("height");
});

Upvotes: 1

Related Questions