Ternstyle

Ternstyle

A web software and design firm

JavaScript Resize Event Function Hangs

There are often functions we wish to perform on our sites when a user resizes the browser. When resizing, your browser’s JavaScript resize event fires for potentially every pixel the browser resizes. At times, the function(s) you wish to tie to the browser resize event can be cumbersome and expensive, which means it takes time to run. Firing a function for potentially every pixel the browser changes can slow down certain browsers and cause them to function unpredictably and less smoothly.

In these times, I use a script I like to call “Resize Intent.” The basic premise is to only run a desired fucntion once a user has finished resizing their browser, when they have resized the browser to the extent they intended. This ensures the function only runs once regardless as to how many times the resize event has been fired.

Let’s take a look.

jQuery.extend({
	resizeIntent : function (f,s) {
		var f = f ? f : function(){};
		var s = s ? s : function(){};
		var timer = time = null;
		jQuery(window).bind('resize orientationchange',function () {
			s();
			time = new Date();
			timer = timer ? timer : setInterval(function () {
				if((new Date()-time) > 500) {
					clearInterval(timer);
					time = timer = null;
					f();
				}
			},100);
		});
	}
});

The first thing you’ll notice is that this function extends jQuery. However, with little effort you can recreate this in pure JavaScript.

The function takes two parameters.

Both are functions. The variable represented by the letter “s” is an event which is fired every time the resize event is fired. This is an optional parameter and needn’t be provided if you don’t intend to fire a function for every pixel change in the browser.

The second parameter is the function you wish to fire after the user stops resizing their browser and it is represented by the letter “f.”

How it works.

Basically, the script starts a timer and checks to see if the time between now and when the resize event last fired is more than 500 milliseconds. If it is, the function you specified is fired and the timer is stopped. Simple as that!

It’s pretty easy to do the same thing for scrolling events which can also fire quickly. Enjoy!



JavaScript Resize Event Function Hangs

Connect with us

We dig the back-and-forth.

Copyright © 2018 Ternstyle LLC. All rights reserved.