0

I am trying to add height to a div dynamically by calculating header div height and footer div height, but it's not working, Here is the example of the code:

I am looking to handle in pure javascript, no JQuery

function contentHeight(e){
  var winH = document.documentElement.clientHeight;
  var headerH = document.getElementsByClassName('header')[0];
  var footerH = document.getElementsByClassName('footer')[0];
  var contentHei = winH - headerH.clientHeight - footerH.clientHeight;
  document.getElementsByClassName('content-inner')[0].clientHeight = contentHei + "px";
}
contentHeight();
<div class="header">
    this is content of header
</div>
<div class="content-inner">
    <!-- Apply dynamic height to this div by calculating header and footer height -->
</div>
<div class="footer">
    footer content
</div>

3
  • Do some basic debugging. Do the values of the variables you're assigning contain what you think they do? Commented May 4, 2018 at 10:32
  • 1
    im pretty sure clientHeight is read only, have you tried height? Commented May 4, 2018 at 10:32
  • @mast3rd3mon I tried height as well but was getting error Commented May 4, 2018 at 11:17

1 Answer 1

6

You need to use style.height in order to adjust the height of an element using JS

function contentHeight(e){
  var winH = document.documentElement.clientHeight;
  var headerH = document.getElementsByClassName('header')[0];
  var footerH = document.getElementsByClassName('footer')[0];
  var contentHei = winH - headerH.clientHeight - footerH.clientHeight;
  document.getElementsByClassName('content-inner')[0].style.height = contentHei + "px";
}
contentHeight();
body {
 margin:0;
}
<div class="header">
    this is content of header
</div>
<div class="content-inner">
    <!-- Apply dynamic height to this div by calculating header and footer height -->
</div>
<div class="footer">
    footer content
</div>

By the way I suspect you want your content to take the free left space of the screen and you can easily do this with pure CSS.

Here is an idea with flexbox:

body {
 margin:0;
 height:100vh;
 display:flex;
 flex-direction:column
}

.content-inner {
  flex:1; /*Fill the empty space*/
  background:yellow;
}
<div class="header">
    this is content of header
</div>
<div class="content-inner">
    
</div>
<div class="footer">
    footer content
</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.