2

I’m trying to make a function that changes the CSS to the current height when I click a button. It won’t read the current height.

var height = $(window).height();

function openNav() {
  document.getElementById("bodypacity").style.height = height;
}
#bodypacity {
  width: 100%;
  background-color: black;
  opacity: 0.4;
  position: absolute;
  z-index: 999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menunav"> <span id="menu" style="" onclick="openNav()">&#9776;</span>
  <a href="index.html"><img id="logo" src="logo.png"></a>
</ul>

5
  • What's wrong with provided code? Anything works unexpected? Commented Jan 4, 2018 at 2:01
  • Where and how is openNav called? Please provide a minimal reproducible example. Commented Jan 4, 2018 at 2:05
  • HTML <ul class="menunav"> <span id="menu" style="" onclick="openNav()">&#9776;</span> <a href="index.html"><img id="logo" src="logo.png"></a> </ul> CSS #bodypacity{ width: 100%; background-color: black; opacity: 0.4; position: absolute; z-index: 999; Commented Jan 4, 2018 at 2:09
  • @CommercialSuicide I want to get the current page height so it would be more flexible than if I put exact size like document.getElementById("bodypacity").style.height = "1000px"; Commented Jan 4, 2018 at 2:12
  • @SteveRuru Please edit your question. Where is the bodypacity element? Commented Jan 4, 2018 at 11:01

1 Answer 1

1

If I understand you correctly, you want to get the height of the window and set the element to equal height. You're very close to achieve that, all you need is to add "px" to the final height, because $(window).height() returns only number, so you can set the actual height using $(window).height() + "px", and it will be document.getElementById("target").style.height = height + "px"; in your case:

var height = $(window).height();
function openNav() {
  document.getElementById("target").style.height = height + "px";
}
html,
body {
  margin: 0;
  padding: 0;
}

#target {
  width: 100%;
  height: 50px;
  background-color: royalblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target">
  <button onclick="openNav()">Set Height</button>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.