Continuously detect window resizing with jQuery
@media statements in stylesheets are fine for defining responsive css changes that activate when the browser window dimensions fall within a certain size range, but what about when you want to activate a javascript function whenever the window is resized, or when it reaches a specific size?
In the example below, jQuery is used to bind a simple function to the window.resize event. The function creates a smoothly changing display in the upper right corner of the window, document and screen dimensions.
if($("body").hasClass( "metrics" )){ $(window).bind("resize", changemetrics); } function changemetrics(){ var wheight = $(window).height(); // returns height of browser viewport var dheight = $(document).height(); // returns height of HTML document var wwidth = $(window).width(); // returns width of browser viewport var dwidth = $(document).width(); // returns width of HTML document var sheight = screen.height; var swidth = screen.width; $('#screenmetrics').html( 'window height ='+ wheight+', window width'+wwidth+'doc width='+dwidth+', doc height ='+dheight+ 'sheight= '+sheight+ ', swidth='+swidth); }
Resources:
- How to get web page size, browser window size, screen size in a cross-browser way? (Stack Overflow)
- jQuery .bind()