Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: dynamic height() with window resize()

Tags:

I'm having an issue identical to this poster: Jquery problem with height() and resize()

But the solution doesn't fix my issue. I have three stacked divs, and I want to use JQuery to make the middle one adjust in height to 100% of the window height, minus the height (23px * 2) of the other top & bottom divs. It works on resize, but it's off (short) by 16px when the document initially loads.

HTML

<body> <div id="bg1" class="bg">top</div> <div id="content">     help me. seriously. </div> <div id="bg2" class="bg">bottom</div> </body> 

CSS

html, body {     width:100%;     height:100%; }  .bg { width:315px; height:23px; margin:0 auto; text-indent:-9000px; }  #bg1 {background:url(../images/bg1.png) 0 50% no-repeat;} #bg2 {background:url(../images/bg2.png) 0 50% no-repeat;}  #content { width:450px;  margin:0 auto; text-align: center; } 

JQuery

$(document).ready(function(){     resizeContent();      $(window).resize(function() {         resizeContent();     }); });  function resizeContent() {     $height = $(window).height() - 46;     $('body div#content').height($height); } 
like image 331
Gregir Avatar asked Nov 15 '11 02:11

Gregir


People also ask

How to use window resize function in jQuery?

jQuery resize() Method The resize event occurs when the browser window changes size. The resize() method triggers the resize event, or attaches a function to run when a resize event occurs.

How does jQuery calculate window height?

Hope this helps. Basically, $(window). height() give you the maximum height inside of the browser window (viewport), and $(document). height() gives you the height of the document inside of the browser.

How dynamically change the height of a div?

The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement.


1 Answers

I feel like there should be a no javascript solution, but how is this?

http://jsfiddle.net/NfmX3/2/

$(window).resize(function() {     $('#content').height($(window).height() - 46); });  $(window).trigger('resize'); 
like image 64
mrtsherman Avatar answered Oct 05 '22 05:10

mrtsherman