Reputation: 63
My goal is to prevent the js from loading on an element when the browser width is less than 500px. Basically, I don't want it to load on most mobile devices.
var mq = window.matchMedia( "(max-width: 500px)" );
if (mq.matches) {
// Don't load function //
}
else {
// Load function //
}
It seems straightforward, and when I try it on my laptop, it works perfectly. At over 500px and the js loads. At under or equal to 500px, it doesn't load.
On my phone, however, my js media query doesn't work because the function loads. Someone suggested that it might have to do with my meta tag.
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
I'm not sure what I'm doing wrong, but I can't seem to successfully relay the mobile browser width to javascript. Any help is greatly appreciated.
Upvotes: 0
Views: 81
Reputation: 4843
When it comes to mobile browsers you can get funky results by using max-width: 500px
media queries, because of the high pixel densities in mobile screens. Your best bet is to use device
media queries, e.g. max-device-width
. So in your case it will look like this:
var mq = window.matchMedia("(max-device-width: 500px)");
if (mq.matches) {
// Don't load function //
}
else {
// Load function //
}
Upvotes: 1