Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Jquery resize function help?

Hello all. Here's the situation. I would like to display my "main" container div at 100% of the window width and height. There will be other content below the fold, so a simple 100% height in the CSS won't work. I have used some JavaScript to remedy this as you can see below. My problem is that upon window resizing, the script needs to grab the new window height and adjust the container div accordingly. Unfortunately, the resize event isn't triggering anything, and I see no errors in the console. The div only resizes again upon page reload.

Sorry, I'm still a JavaScript newb! Any help would be most appreciated. Thanks.

$( document ).ready(function() {
    var $winHeight = $( window ).height();
    $( ".container" ).css({'height' : $winHeight});

    $( window ).resize(function() {
        $( ".container" ).css({'height' : $winHeight});
    });
});

1 Answer

Colin Marshall
Colin Marshall
32,861 Points

The problem is that your $winHeight variable is set when the page loads. You need to bind a variable to the window height inside of the resize() method as well:

$( document ).ready(function() {
    var $winHeight = $( window ).height();
    $( ".container" ).css({'height' : $winHeight});

    $( window ).resize(function() {
        var $newHeight = $( window ).height();
        $( ".container" ).css({'height' : $newHeight});
    });
});

Thanks so much, Colin! Your help with my nonsensical code is most appreciated :)