Dynamically resize a div using jQuery

html, javascript, jquery

Solution

There are a few things going wrong here:

- Your code will execute straight away before your document has finished loading.

- Your code will execute only on load of the the script, not on resize

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

});

Problem

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?

Original source

Related problems