100% height - pixels

I’m trying to write a jQuery script to resize a Google map I have wrapped in div#map. I want the map to be 100% of the window size minus 120px for the header and topbar. Does anyone know how to have this work everytime the window is resized? I’m new to jQuery and am having some issues getting this to work. Thanks!


$(window).resize(function() {
	  $('#map').height() = ($window).height() - 120;
});

Hi there.

I’ve put up a jsFiddle to demo this behaviour.

Basically the important things are:

Basic CSS to get the layout


#header {
    height:120px; 
    width:100%;
    background: #ccc;
}


#map {
    height:500px; /* Just a minimum height */
    width:100%;
    background: #aaa;
}

Basic instance of Google Maps


var googleMap;
function map_init() {
    var myOptions = {
        zoom: 8,
        center: new google.maps.LatLng(-34.397, 150.644),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    googleMap = new google.maps.Map(document.getElementById('map'), myOptions);
}


google.maps.event.addDomListener(window, 'load', map_init);

The JS that handles the resizing


//set the minimum height of the map
var minSize = 500;
//cache reference to jQuery vars we need in the resize method
var $map = $("#map");
var $win = $(window);


//start out by setting the height
$map.height($win.height()-120);

// You may also to want to look in to using a "Throttler" like jQuery.throttle 
// to limit the amount of times this gets called, especially if you have a lot
// of objects on the map (pins, lines, etc).
// e.g. http://benalman.com/projects/jquery-throttle-debounce-plugin/
$(window).resize(function(){
    //make sure the new size is at least the min-height we want
    var newSize = $win.height()-120;


    if ( parseInt(newSize, 10) < minSize ) {
        newSize = minSize;
    }


    $map.height(newSize);
});

How can I make this go 100% of the height remaining under the header.

The JS fiddle linked above should be doing just that.

I’ve updated it so it puts an overflow:hidden; on the body to make sure that it doesn’t get a scrollbar (in case there is extra margin/padding for some reason)