Dan Lee
Dan Lee

Reputation: 704

Resetting div height when window is resized

I'm trying to set the height on a responsive layout using javascript. I notice that when using the following function the height does get applied when making the window narrow but doesn't get reset when moving back to the original wider window position. The height is retained no matter what the window size is. How do I reset the div to the original height?

$(function () {

    $(window).on("load resize", function () {
        console.log($(this).width());
        if ($(this).width() < 1025) {
            $(".case-study-child").height($(".case-study-parent").height());
        } 
    }).trigger('resize');

});

Upvotes: 0

Views: 1973

Answers (1)

Nathan Hase
Nathan Hase

Reputation: 659

The best way to do this is with proper arrangement of the markup and use of responsive styles. However there may be a reason that responsive style is insufficient and it needs to be solved with js:

You'll need to define the 'full screen' height of the .case-study-child div so it can be set when the screen width goes above 1024. This is necessary in case the page is originally loaded at < 1024

$(function () {

    // need to know what the div height should be when the page width is >= 1025px
    window.fullScreenHeight = "250px";

    $(window).on("load resize", function () {

        console.log($(this).width());

        // get the height to set the div to based on the screen width
        var newDivHeight = $(this).width() < 1025 ? $(".case-study-parent").height() : window.fullScreenHeight;

        $(".case-study-child").height(newDivHeight);

    }).trigger("resize");

});

Upvotes: 1

Related Questions