why my animate to change width%height doesnt work

Viewed 28
$(".btn").click(function(){
            if($($(this).parent().parent()).width() == "100%" ){
                $(this).parent().parent().stop().animate({
                    top : 0,
                    left : 0,
                    width : "500px",
                    height : "300px",
                })
            }else{
                $(this).parent().parent().stop().animate({
                    top : 0,
                    left : 0,
                    width : "100%",
                    height : "100%"
                })
            }
        })

here is my code. i don't know why my first animation doesn't work. animate width to 100% works well, but the opposite(to 400px) does not.

1 Answers

's .width() method will return the actual width in pixels. It will never be "100%".

So you need to check for your 100% by comparing the width with the parent's .width()

var maxwidth = $(this).parent().parent().parent().width();
if ($(this).parent().parent().width() == maxwidth) {

(I recommend using .closest("class") instead of multiple .parent() calls)

Updated snippet with some derived HTML to demonstrate:

$(".btn").click(function() {
  console.log($("#box").width())
  //if ($("#box").width() == "100%") {
  var maxwidth = $("#box").parent().width();
  if ($("#box").width() == maxwidth) {
    $("#box").stop().animate({
      top: 0,
      left: 0,
      width: "50px",
      height: "30px",
    })
  } else {
    $("#box").stop().animate({
      top: 0,
      left: 0,
      width: "100%",
      height: "100%"
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='btn'>
  click me
</button>
<div id="wrapper" style='width:80px;height:50px;border:1px solid red;'>
  <div id="box" style='border:1px solid blue;width:50px;height:30px;'>

  </div>
</div>

Related