I have a div (id="mainDiv") which I need to dynamically resize if the user changes the size of their browser window. I have written the following code to try and get this to work however this doesn't seem to be setting the height of my div:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
var height = $(window).height();
$("#mainDiv").height(height);
</script>
<body>
<div id="mainDiv"></div>
</body>
I don't know much jQuery, am I making an obvious mistake?
There are a few things going wrong here:
You need to handle the browser resize event to wait for the browser to resize then get the dimensions of the window and apply accordingly. You'd do this by handling the window.resize event liks this:
var $win = $(window);
$win.on('resize',function(){
$("#mainDiv").height($win.height());
});
What you probably want to do is wait for for a resize to finish to by adding a timeout so that it doesn't fire too often as well:
var timer,
$win = $(window);
$win.on('resize',function(){
clearTimeout(timer);
timer = setTimeout(function(){
$("#mainDiv").height($win.height());
}, 500);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With