Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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