Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically resize a div using jQuery

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?

like image 590
CJH Avatar asked Jun 06 '26 09:06

CJH


1 Answers

There are a few things going wrong here:

  1. Your code will execute straight away before your document has finished loading.
  2. Your code will execute only on load of the the script, not on resize
  3. You're not setting the height of your mainDiv - you're setting the height of another element with the id: accordianMain (but I'm guessing you know that).

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);

});
like image 76
Lewis Avatar answered Jun 07 '26 23:06

Lewis