jQuery: detecting a browser resize

Cool Guy Yo picture Cool Guy Yo · Jan 9, 2010 · Viewed 18.5k times · Source

I am using this script from snipplr, How would I set it so the container div is 100px less than the newWindowHeight height, like -100 or something.

<script type="text/javascript" charset="utf-8">
$(document).ready(function(){

//If the User resizes the window, adjust the #container height
$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
    var newWindowHeight = $(window).height();
    $("#container").css("max-height", newWindowHeight );
}

});         
</script>

Answer

Sampson picture Sampson · Jan 9, 2010

The script you found over-complicated the issue. The following worked for me:

$(function(){

    // Cache reference to our container
    var $container = $("#container");

    // A function for updating max-height
    function updateMaxHeight () {
        $container.css("max-height", $(this).height() - 100);
    }

    // Call updateMaxHeight when browser resize event fires
    $(window).on("resize", updateMaxHeight);

});

One warning is that the resize event gets called a lot when resizing the browser; it's not just called after the browser has been resized. As a result, you could have the callback function being called hundreds of times - this is generally a bad idea.

The solution would be to throttle, or debounce the event. Throttling means you won't let the callback be fired more than x times in a span of time (maybe 5 times a second). Debouncing means you fire the callback after a certain span of time has passed from the last resize event (wait until 500 milliseconds after a resize event).

jQuery doesn't presently support a throttle or debounce option, though there are plugins. Other popular libraries you may have used do have these features, such as underscore:

$(function(){

    // Cache reference to our container
    var $container = $("#container");

    // A function for updating max-height
    function updateMaxHeight () {
        $container.css("max-height", $(this).height() - 100);
    }

    // Version of updateMaxHeight that will run no more than once every 200ms
    var updateMaxHeightThrottled = _.throttle(updateMaxHeight, 200);

    // Call updateMaxHeightThrottled when browser resize event fires
    $(window).on("resize", updateMaxHeightThrottled);

});