Responsive Window Resize Detection with jQuery

19th July 2014  -  by Alex Bimpson  -  0 Comments

When building responsive websites or apps, I pretty quickly found myself needing a quick and reliable way to detect screen size and fire off various functions whenever the browser window is resized or device orientation changes.

Over time, I've created and refined a handy jQuery function that does exactly this, storing the browser window dimensions and executing custom functions if either the width or height is changed, so I thought I'd share it here in case it can help anyone else!

If you want to jump straight to the goods, you can find the complete code here. For the rest of you, here's a little overview of how it works...

Firstly, we're going to set this up as a javascript object, to keep things organised. Simply declare your new object with an open brace, and then we'll populate it

var windowsize = {

Next, we've got some basic configuration and data variables for storing important information, such as the current width and height of the window. If you ever need to, you can turn the entire thing off by setting windowsize.use to false, and nothing will happen on resize.

At any time you can reference windowsize.w and windowsize.h to get the current pixel dimensions of the browser window.

	//CONFIG
	use: true, //turn the window size function on or off
	freq: 100, //timeout between running of the function
	//DATA
	w: 0 //stores window width,
	h: 0 //stores window height,
	timeout: null //stores our function on a timeout,

We want to ensure that window resizing won't cause our custom code to execute for every single pixel of movement as you resize the window - this can really slow things down. Instead, we will wait until the size has remained consistent for windowsize.freq milliseconds (defined in our config as 100) before actually doing anything else. This suggests that the user has temporarily finished resizing the window.

This first function, windowsize.run(), will be called whenever the browser window resizes. As explained, it sets a short timeout to ensure it doesn't execute subsequent complex code a hundred times in the few seconds it takes a user to resize their window. The timeout will be continually reset until the user stops adjusting their window. Note: we'll come back to that "force" parameter later.

	//RUN
	run: function(force){
		if(windowsize.use == true){
			if(force == true){
				windowsize.func(force);
			}else{
				clearTimeout(windowsize.timeout);
				windowsize.timeout = setTimeout(function(){
					windowsize.func(force);
				}, windowsize.freq);
			};
		};
	},

You've then got windowsize.func() - once the browser window has stayed a consistent size for windowsize.freq milliseconds, we get the window's new dimensions and check whether they're different to the currently stored dimensions. If they are, it'll run more functions: windowsize.w_func, windowsize.h_func and windowsize.x_func.

	func: function(force){
		var newWidth = $(window).width();
		var newHeight = $(window).height();
		if(force == true){
			windowsize.w = newWidth;
			windowsize.h = newHeight;
			windowsize.w_func();
			windowsize.h_func();
		}else{
			if(newWidth!=windowsize.w){
				windowsize.w_func();
			};
			if(newHeight!=windowsize.h){
				windowsize.h_func();
			};
			if(newWidth!=windowsize.w || newHeight!=windowsize.h){
				windowsize.x_func();
			};
			windowsize.w = newWidth;
			windowsize.h = newHeight;
		};
	},

It's those last 3 functions, below, where you want to put your own code for executing after a resize. I've written handy comments, e.g. "code here will run if the width changes", to help make this clear.

	//FUNCTIONS
	w_func: function(){
		//code here will run if the width changes
	},
	h_func: function(){
		//code here will run if the height changes
	},
	x_func: function(){
		//code here will run if the either the width or height changes
	}

Finally, don't forget to close the windowsize object with another brace.

};

Running the function

All you need to do now is tell your app to actually run this function. As well as telling it to run on resize, You'll probably want to run the function on document ready and on window load, to make sure your custom code executes when the page first loads.

The code for this is simple:

$(document).ready(function() {
	windowsize.run(true);
});
$(window).load(function(){
	windowsize.run(true);
});
$(window).resize(function(){
	windowsize.run();
});

This is where the "force" variable comes in. By setting this as true, we bypass the timeout, and also run our custom code regardless of whether the window has changed size or not. I always use this on both $(document).ready and $(window).load, as I want to ensure all subsequent custom code will be executed as quickly as possible, and again once everything has loaded.

The $(window).resize part will also fire on mobile devices if your device orientation changes, i.e. from landscape to portrait.

Wrap up

That's about it - hopefully it's all pretty straightforward, and hopefully it'll help some of you! You can browse the complete code in the resource library. And of course, if you've got any questions or suggestions on how to improve upon this, then do let me know in the comments below!

by Alex Bimpson

Web designer and developer, and founder of Prrple. Works at Kerve, and studied Architecture at the University of Bath.

Comments

Keep Up To Date

Want to ensure you always catch our latest posts? You can follow us on Twitter, like us on Facebook, and even subscribe to a good old fashioned RSS feed. Just click the relevant links below to make sure you never miss a thing.