How to detect the width of a web browser using jQuery
Detecting the width of a browser window can be very useful when designing a website, it allows you to create a more responsive design which is suited to the current browser dimensions.
Using the small chunk of jQuery below, you can easily detect the current width of a web browser & perform various actions when the width reaches a particular range of values. When redeveloping my site I opted to use this method to add a different body class to the site when the browser width reaches a below particular points: ‘smaller’ when the width reaches below 960px but greater than 400px and ‘smallest’ when the width is below ‘400px’. The additional body classes then allowed me to alter the position/style of particular elements on the page.
(function($){
//detect the width on page load
$(document).ready(function(){
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 400){
jQuery('body').addClass('probably-mobile');
}
});
//update the width value when the browser is resized (useful for devices which switch from portrait to landscape)
$(window).resize(function(){
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 400){
jQuery('body').addClass('probably-mobile');
}
});
})(jQuery);
</code>
As well as implementing this technique on my site, I also created the page: what is my browser width? as a demo.
Using the code above can be really useful when adapting your website to fit a mobile browser however it’s not a perfect solution - shrinking images down to a width of 320px can often render them useless, especially with intricate diagrams. I’m really interested in exploring the concept of feeding the width information to a server side script via AJAX, this could then be used to optimize the next page load for the current user, remove large images or anything that may take longer to load over a mobile network.
I’m still learning about responsive web design & the example above is just one possible method of implementing it, CSS3 media queries is another possible method I’m looking to explore.
Used the code above? Let me know in the comments!
Filed under: