I'm trying to let jQuery take care of a menu, while CSS does something to the window background when resizing the browser.
So jQuery does something like this:
if ( $(window).innerWidth() < mediaQueries['small']) {
// (where 'small' would be 966)
// Perform jQuery stuff on a menu ul
}
And CSS has something like this:
@media all and (max-width: 966px) {
body {
background: url(smallback.jpg) no-repeat 0 0;
}
}
When using Firefox, there's a gap of 17 pixels (which seems to be the vertical scrollbar width) in which the jQuery stuff is already handled, but the CSS is not.
As other browsers may use different widths for their scrollbars, just adding 17px to the CSS won't really fix the problem. So how do I get jQuery to take the scrollbars into account? $(window).innerWidth()
doesn't seem to do that for me.
Any help would greatly be appreciated.
Open this page in Firefox, Opera or IE for an isolated version of the problem. (Chrome and Safari don't suffer from this problem. Thusfar: Webkit: +1, Gecko: -1, Trident: -1, Presto: -1.)
window.matchMedia
is a way you can fire events when media selectors kick on or off. It's new so not widely supported, but seems pretty useful."Using media queries from code" from MDN
If you happen to be using Modernizr, you can include the media query polyfill, which simplifies media query checks to:
Which is conveniently identical to your CSS:
If you can't use Modernizr's polyfill, then stick with checking against
Math.max(document.width, window.innerWidth)
.In addition to the solution of JackieChiles:
Using
will always get you the width without scrollbars in any browser.This solution is (IMHO) better because the JS does not depend on any CSS.
Thanks to JackieChiles and Arjen for this solution!
My solution to triggering JavaScript at the exact same time as media queries (even in the face of device or browser quirks as seen here) is to trigger my
window.resize
logic in response to a change that the media query made. Here's an example:CSS
JavaScript
In this example, whenever
#myDiv
changes size (which will occur when the media query is triggered), your jQuery resize logic will also be run.For simplicity I used an element width, but you could easily use whatever property you are changing, such as the
body
background.Another advantage of this approach is that it keeps the
window.resize
function as lightweight as possible, which is always good because it is called every single time the window size changes by a single pixel (in most modern browsers anyway).The bug that you encountered seems to me to be a browser-specific problem, as you said. Although it seems incorrect intuitively, Firefox (and other browsers with the issue) actually seems to match the W3C recommendation for media queries more closely than the Webkit browsers. The recommendation states that the viewport width includes scrollbars, and JavaScript window width does not seem to include scrollbars, hence the disrepancy.