Chrome for Android firing resize event?

by
22 April 2015 0 comments
Chrome for Android firing resize event?

I found a strange and really annoying issue when testing a newly deployed responsive website on my Android Sony Xperia Z3 in that whenever I scrolled up and down, any JavaScript that I had within a resize event handler got fired even though the website wasnt being resized.

Upon investigating, it turned out that due to the way Chrome on Android shows and hides the UI bar at the top of the viewport when you are scrolling either up or down, a resize event is actually fired due to the height of the viewport changing!

A simple work around...

The best way to get around this I found is to cache the width on load and then check against that width on resize.  I normally throttle my resize event so I don't get continuous events being fired, so the code I used to get around this Android issue is below:


// Cache the width
var width = $(window).width();

// On resize
$(window).on("resize", function () {

	// Throttle the resize event
	clearTimeout(this.id);
	this.id = setTimeout(function () {
		if (width !== $(window).width()) {

			// your resize code	
			
            // Update the width variable
	        width = $(window).width();
		}
	}, 250);   
});

If anyone has a better solution to this, I'd be grateful to hear about it, but this seems like a good approach to the problem.

← All posts

Leave a comment

Send us a message

Vital Works would love to hear from you. If you have a project in mind or have a general question, then please get in touch.