Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Live Detect Browser Size - jQuery / JavaScript

Tags:

Is there a jQuery plugin or a way using straight JavaScript to detect browser size.

I'd prefer it is the results were 'live', so if the width or height changes, so would the results.

like image 544
user1658756 Avatar asked Oct 08 '12 11:10

user1658756


People also ask

How do I find my browser viewport size?

You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.

How does jQuery calculate window height?

height() method is recommended when an element's height needs to be used in a mathematical calculation. This method is also able to find the height of the window and document. $( document ). height();

What is window innerWidth?

The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present. More precisely, innerWidth returns the width of the window's layout viewport.


1 Answers

JavaScript

function jsUpdateSize(){
    // Get the dimensions of the viewport
    var width = window.innerWidth ||
                document.documentElement.clientWidth ||
                document.body.clientWidth;
    var height = window.innerHeight ||
                 document.documentElement.clientHeight ||
                 document.body.clientHeight;

    document.getElementById('jsWidth').innerHTML = width;  // Display the width
    document.getElementById('jsHeight').innerHTML = height;// Display the height
};
window.onload = jsUpdateSize;       // When the page first loads
window.onresize = jsUpdateSize;     // When the browser changes size

jQuery

function jqUpdateSize(){
    // Get the dimensions of the viewport
    var width = $(window).width();
    var height = $(window).height();

    $('#jqWidth').html(width);      // Display the width
    $('#jqHeight').html(height);    // Display the height
};
$(document).ready(jqUpdateSize);    // When the page first loads
$(window).resize(jqUpdateSize);     // When the browser changes size

jsfiddle demo

Edit: Updated the JavaScript code to support IE8 and earlier.

like image 181
Matt Coughlin Avatar answered Oct 26 '22 07:10

Matt Coughlin