Optional Javascript Execution based on Media Queries

10,697

Solution 1

How about using javascript for that?

<script type="text/javascript">

if (screen.width < 980) { 

document.write('<link href="UrLowRes.css" type="text/css" rel="stylesheet"/>');

} else { 

document.write('<link href="UrlHighRes.css" type="text/css" rel="stylesheet"/>');

} 

</script>

Solution 2

The current accepted answer is not good enough, you should check window.matchMedia

You can detect viewport dimension changes, but you must calculate factors such as orientation and aspect ratios and there is no guarantee our calculation will match our browser assumptions when it applies media query rules.

I mean, you can calculate X, but your browser assumption can be Y. So i think is better to use same browser rules, and window.matchMedia does it

var jmediaquery = window.matchMedia( "(min-width: 480px)" )
if (jmediaquery.matches) {
    // window width is at least 480px
}
else {
    // window width is less than 480px
}

You can even receive query notification using a listener

var jmediaquery = window.matchMedia("(orientation: portrait)");
jmediaquery.addListener(handleOrientationChange);
handleOrientationChange(jmediaquery);

function handleOrientationChange(jmediaquery) {
    if (jmediaquery.matches) {
        // orientation changed
    }
}

If you no longer need to receive notifications about changes simply call removeListener()

jmediaquery.removeListener(handleOrientationChange);

Solution 3

You might find the Enquire.js library helpful:

http://wickynilliams.github.com/enquire.js/

CSS-Tricks article: http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/

Solution 4

You can also using a plugin called minwidth:

minwidth(940, function () {
  //do whatever you need
});

But it only works when the page loads not when resizing..

http://edenspiekermann.com/en/blog/responsive-javascript-helpers

Share:
10,697
Jeremy Harris
Author by

Jeremy Harris

I am a web developer and enjoy spending my free time learning new technologies, playing video games, fishing, and just being outside when I can.

Updated on June 12, 2022

Comments

  • Jeremy Harris
    Jeremy Harris about 2 years

    I'm trying to figure out how I can optionally run a block of javascript based on the current device/media query. I'm using Twitter Bootstrap and have essentially two versions of media queries:

    @media (min-width: 980px) { ... } <!-- Desktops -->
    @media (max-width: 979px) { ... } <!-- Smaller screens/tablets/phones -->
    

    I have a map that I generate, but am not showing it in the mobile/small screen version forb andwidth reasons. Yet, the javascript still executes in the background even though you can't see it on the mobile screen. So, I'm trying to find a way in javascript where I can do something like:

    // Imaginary function
    var screenType = getScreenType();
    
    if(screenType == 1) {
       // Load map
    }
    

    I've read about people setting CSS properties to specific values in their media queries and then trying to find that element in the DOM based on the CSS property, but there has got to be a better way. Any ideas?

  • Jeremy Harris
    Jeremy Harris over 11 years
    Interesting, I think this will be an acceptable solution. Thanks.
  • Jeremy Harris
    Jeremy Harris over 11 years
    Very useful library, although I'm thinking in my particular instance, pure Javascript is probably the lightest weight solution. Thanking for pointing out Enquire though, I will probably use it in future projects.
  • jfriend00
    jfriend00 over 11 years
    If your window width can be resized, you might need to add monitoring for window width changes?
  • Jeremy Harris
    Jeremy Harris over 11 years
    My primary concern is not wasting bandwidth on mobile devices, so in this case width changes are unlikely to affect my goal.
  • frenchie
    frenchie over 11 years
    @jfriend00: screen.width or screen.height deal with the size of the display, not the size of the window. The size of the display is fixed by the hardware and cannot change.
  • jfriend00
    jfriend00 over 11 years
    @frenchie - what about when the device is rotated?
  • frenchie
    frenchie over 11 years
    @jfriend00: good point. I think the OP should check for that: either the values return the same regardless of the orientation of use something like if (Math.Min(screen.width, screen.height)) {...}
  • Jeremy Harris
    Jeremy Harris almost 11 years
    Good Idea! Thanks for keeping this question up to date.
  • StinkyCat
    StinkyCat over 10 years
    The accepted answer doesn't let you check the result if you resize your browser window, so for developing purpose, this answer is better. thks!
  • neophyte
    neophyte over 7 years
    great insight, +1
  • door_number_three
    door_number_three over 6 years
    This is great to know! Thanks!
  • Steve06
    Steve06 over 4 years
    This is sub-par as an answer. @yeradis answer stackoverflow.com/a/18174378/632333 is the way to go!
  • Steve06
    Steve06 over 4 years
    That's how we do it! +1