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:
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
#my-div
{
width: 100px;
}
@media all and (max-width: 966px)
{
#my-div
{
width: 255px;
}
}
JavaScript
var myDivWidth;
$(document).ready(function() {
myDivWidth = $('#myDiv').width();
$(window).resize(function () {
if ($('#myDiv').width() != myDivWidth) {
//If the media query has been triggered
myDivWidth = $('#myDiv').width();
//Your resize logic here (the jQuery menu stuff in your case)
}
});
});
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.