How can I detect window size with jQuery?

Solution 1:

You cannot really find the display resolution from a web page. There is a CSS Media Queries statement for it, but it is poorly implemented in most devices and browsers, if at all. However, you do not need to know the resolution of the display, because changing it causes the (pixel) width of the window to change, which can be detected using the methods others have described:

$(window).resize(function() {
  // This will execute whenever the window is resized
  $(window).height(); // New height
  $(window).width(); // New width
});

You can also use CSS Media Queries in browsers that support them to adapt your page's style to various display widths, but you should really be using em units and percentages and min-width and max-width in your CSS if you want a proper flexible layout. Gmail probably uses a combination of all these.

Solution 2:

You make one div somewhere on the page and put this code:

<div id="winSize"></div>
<script>
    var WindowsSize=function(){
        var h=$(window).height(),
            w=$(window).width();
        $("#winSize").html("<p>Width: "+w+"<br>Height: "+h+"</p>");
    };
   $(document).ready(WindowsSize); 
   $(window).resize(WindowsSize); 
</script>

Here is a snippet:

var WindowsSize=function(){
    	var h=$(window).height(),
    		w=$(window).width();
    	$("#winSize").html("<p>Width: "+w+"<br>Height:"+h+"</p>");
 };
 $(document).ready(WindowsSize); 
 $(window).resize(WindowsSize); 
#winSize{
  position:fixed;
  bottom:1%;
  right:1%;
  border:rgba(0,0,0,0.8) 3px solid;
  background:rgba(0,0,0,0.6);
  padding:5px 10px;
  color:#fff;
  text-shadow:#000 1px 1px 1px,#000 -1px 1px 1px;
  z-index:9999
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="winSize"></div>

Of course, adapt it to fit your needs! ;)

Solution 3:

You can get the values for the width and height of the browser using the following:

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

To get notified when the browser is resized, use this bind callback:

$(window).resize(function() {
    // Do something
});

Solution 4:

Do you want to detect when the window has been resized?

You can use JQuery's resize to attach a handler.

Solution 5:

//get dimensions 
var height = $(window).height();
var width = $(window).width();

//refresh on resize
$(window).resize(function() {
  location.reload(true)
});

not sure if you wanted to tinker with the dimensions of elements or actually refresh the page. so here a bunch of different things pick what you want. you can even put the height and width in the resize event if you really wanted.