1

I want to change the height of the div by clicking it.

Why it doesn't work at the first clicking but the second?

I don't know why, but the height of the div is "" (in the second clicking is 20px because of the else condition)

If I define the height of the div in the html element (style="height: 20px"), it works.

<html>
<head>
<script>
    function divOpen() {
        var divHeight= document.getElementById("divBottom").style.height;
        if (divHeight=="20px") {
        document.getElementById("divBottom").style.height="200px"; 
        }
        else {
            document.getElementById("divBottom").style.height="20px"; 
        }
    }


</script>

    <style>
        div{
            border:solid 1px gray; 
            width:200px;
            height:20px;   
        }
        .divBottom {
            position: fixed;
            bottom: 0;
        right: 20px;
        cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="divBottom" id="divBottom" onclick="divOpen()"></div>
</body>
</html>

so I know how to fix it, but I don't know why the height is empty in the first clicking.

Please let me know..

any help appreciated!

Alon Shmiel
  • 6,753
  • 23
  • 90
  • 138

1 Answers1

5

In the initial click the height style property of your div is '' because you haven't set it.

There is a difference between setting height through the style property and by using a class. Try to refactor your code and make it use offsetHeight instead of style.height.

JavaScript

function divOpen() {
  var divHeight= document.getElementById("divBottom").offsetHeight;
  console.log(divHeight);
  //22 because of the border
  if (divHeight == 22) {
    document.getElementById("divBottom").style.height="200px"; 
  }
  else {
    document.getElementById("divBottom").style.height="20px"; 
  }
}

DEMO

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68