I only need to know a cross-browser and reliable way to detect the browser width so JS returns exactly the same value as media queries does?
This should detect it correctly on desktops, laptop, tablets and mobiles.
I believe in jQuery you can perform $(window).width()
And you can attach an event to resize(), so it runs when the user resizes their browser window
// grab the width
var width = $(this).width();
Granted, you will need to run this function on DOM load too, as the resize event is only called when the window size changes.
Just remembered, you might also have success with document.documentElement.clientWidth and/or document.body.clientWidth
Different browsers track the viewport width in different fields. The following is the shortest code that will get the value from whichever of the three places that the browser uses.
var viewportWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
This topic is now closed. New replies are no longer allowed.