Home » Jquery » Jquery Change Height based on Browser Size/Resize

Jquery Change Height based on Browser Size/Resize

Posted by: admin November 29, 2017 Leave a comment

Questions:

I was wondering if there was a way to determine the height/width of a browser.
What i’m trying to do is set a height on a div to 500px when the browser size is 1024×768, and for anything lower i’d like to set it to 400px.

Thanks in advance

Answers:

If you are using jQuery 1.2 or newer, you can simply use these:

$(window).width();
$(document).width();
$(window).height();
$(document).height();

From there it is a simple matter to decide the height of your element.

Questions:
Answers:
$(function(){
    $(window).resize(function(){
        var h = $(window).height();
        var w = $(window).width();
        $("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
    });
});

Scrollbars etc have an effect on the window size so you may want to tweak to desired size.

Questions:
Answers:

Building on Chad’s answer, you also want to add that function to the onload event to ensure it is resized when the page loads as well.

jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);

function resizeFrame() 
{
    var h = $(window).height();
    var w = $(window).width();
    $("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
}

Questions:
Answers:

Pay attention, there is a bug with Jquery 1.8.0, $(window).height() returns the all document height !

Questions:
Answers:

I have the feeling that the check should be different

new:
h < 768 || w < 1024