How to use javascript conditionally like CSS3 media queries, orientation?

42,419

Solution 1

You can use window.matchMedia():

Test a mobile device media query

if (matchMedia('only screen and (max-width: 480px)').matches) {
  // smartphone/iphone... maybe run some small-screen related dom scripting?
}

Test landscape orientation

if (matchMedia('all and (orientation:landscape)').matches) {
  // probably tablet in widescreen view
}

Currently supported in all modern browsers (more details)

Polyfill for old browsers: https://github.com/paulirish/matchMedia.js/

Solution 2

...I want to run a javascript only if max-width of browser is 1900px and min-width is 768

EDIT: Actually, that was all wrong. If you're using a mobile device, use:

function doStuff(){
    landscape = window.orientation? window.orientation=='landscape' : true;

    if(landscape && window.innerWidth<1900 && window.innerWidth > 768){
        //code here
    }
}
window.onload=window.onresize=doStuff;
if(window.onorientationchange){
    window.onorientationchange=doStuff;
}

Solution 3

I can think of a quick solution: Apply some styles conditionally to an invisible div, and check if they are applied with javascript:

div#test { display: none }
@media only screen and (width : 1024px) and (orientation : landscape) {
    div#test { background-color: white; }
}
if(document.getElementById('test').style.backgroundColor == 'white')
    mediaSelectorIsActive();
Share:
42,419

Related videos on Youtube

Jitendra Vyas
Author by

Jitendra Vyas

Hi, I am Jitendra a front-end developer from India specializing in web standards, accessibility, and usability based development.

Updated on April 01, 2021

Comments

  • Jitendra Vyas
    Jitendra Vyas about 3 years

    How to use javascript conditionally like CSS3 media queries, orientation?

    For Example I can write css for specific

    @media only screen and (width : 1024px) and (orientation : landscape) {
    
    .selector1 { width:960px}
    
    }
    

    Now I want to only run some javascript if it match the same conditions

    like

    @media only screen and (width : 1024px) and (orientation : landscape) {
    
    A javascript code here
    
    }
    

    I have a external javascript for example http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js and it should be only run on specific screen size and orientation

    • Eric
      Eric over 12 years
      Why would you want jQuery to only run on one size and orientation?
    • Eric
      Eric over 12 years
      What do you want to happen if the orientation or size changes after loading? (device rotated, window resized, etc)
    • Jitendra Vyas
      Jitendra Vyas over 12 years
      i want to use a image resize jquery plugin only if max-width:1025px and max-width:2048px
    • Eric
      Eric over 12 years
      You should include the library no matter what. Just don't use the functions unless the screen is of the correct size
    • Jitendra Vyas
      Jitendra Vyas over 12 years
      @Eric - this is the plugin which I want to use to image re-sizing ollicle.com/projects/jquery/imagefit/eg only if max-width:1025px and max-width:2048px Why I'm using this plugin because I don't know the technique used by google chrome new tab. stackoverflow.com/questions/7613810/…
    • Eric
      Eric over 12 years
      I'm not sure you understand how jQuery plugins work. By default, they don't actually do anything. All they do is include some code that allows you to do something. In the case of your plugin, $(selector).imagefit() does the magic.
    • Emil Stenström
      Emil Stenström over 12 years
      @Jitendra: Here's a better way to resize images for mobile phones: sencha.com/learn/how-to-use-src-sencha-io
    • rlcrews
      rlcrews over 11 years
      I would recommend not including the library just to include it. Adding a reference to the library and not using it only bloats the packets being requested and sent to the client.
    • Emil Stenström
      Emil Stenström almost 9 years
      @JitendraVyas: Would you mind marking my answer as accepted? It has 42 votes, so I think it should be considered the best one.
  • Rob W
    Rob W over 12 years
    +1 Just finished typing a similar answer, but you were faster.
  • mowwwalker
    mowwwalker over 12 years
    That's what I said, but I think the problem is that the CSS executes instantly based on this example: 1stwebdesigner.com/css/… Which would mean that it wouldn't be instant and you would have to keep checking.
  • mowwwalker
    mowwwalker over 12 years
    I guess my answer is just invisible?
  • Eric
    Eric over 12 years
    @Walkerneo: CSS executing instantly is good! That'd make it happen before the javascript! As for your answer, it's just too vague.
  • Jitendra Vyas
    Jitendra Vyas over 12 years
    @Walkerneo - you are right. I want to run a javascript only if max-width of browser is 1900px and min-width is 768.
  • mowwwalker
    mowwwalker over 12 years
    No, I mean it responds to the content. Did you see the example with the chameleon? It changes colors when you resize the window. The CSS takes effect instantly.
  • Emil Stenström
    Emil Stenström over 12 years
    This means you have to select a random element and change its style to execute some javascript. Doesn't seem like a good idea...
  • Eric
    Eric over 12 years
    @Walkerneo: That's a problem with the original question. The asker hasn't specified what they want to happen if the window is resized. You can't "un-run" the script, and it would probably be a bad idea to rerun it every time the window is resized.
  • mowwwalker
    mowwwalker over 12 years
    @JitendraVyas, What exactly do you mean by that? You can use window.offsetWidth to check the width of their window. You can use window.onresize to check if, after the resize, it's the correct dimensions
  • Eric
    Eric over 12 years
    +1 Probably a cleaner way of doing it than my way.
  • Jitendra Vyas
    Jitendra Vyas over 12 years
    can i put a external javascript inside it?
  • Emil Stenström
    Emil Stenström over 12 years
    This does not take into account the orientation change.
  • Eric
    Eric over 12 years
    @Jitendra: You don't have to! Just let the plugin run anyway, and put $('img').imagefit() inside it.
  • mowwwalker
    mowwwalker over 12 years
    @EmilStenström, Is everyone here talking about with handheld devices? If you are, then it's been going over my head this entire time.
  • Emil Stenström
    Emil Stenström over 12 years
  • Jitendra Vyas
    Jitendra Vyas over 12 years
    @Eric - Can you please answer of this question stackoverflow.com/questions/7613810/… in the Chrome tab , the icons only start to scale after 768px and only scale up-to 1200px. after 1200px and before 768px icons doesn't scale
  • Emil Stenström
    Emil Stenström over 12 years
    @Walkerneo: The original question has orientation: landscape, so I assume that the js in question should only run in that orientation.
  • mowwwalker
    mowwwalker over 12 years
    What do you want to happen if they're not on a mobile device?
  • Jitendra Vyas
    Jitendra Vyas over 12 years
    @Walkerneo - on mobile device I would not re-size the picture. So i will not need any javascript condition
  • mowwwalker
    mowwwalker over 12 years
    @JitendraVyas, but your example code checks for window orientation, which only exists in mobile devices...
  • Jitendra Vyas
    Jitendra Vyas over 12 years
    @Walkerneo - yes I'm considering iPad but not iphone
  • Jitendra Vyas
    Jitendra Vyas over 12 years
  • Yoann
    Yoann over 12 years
    There is a video from Google that explain That : youtu.be/svEg7MiqGf8?t=3m4s
  • lededje
    lededje about 11 years
    Scroll bars throw this out
  • Mohammad
    Mohammad over 5 years
    I think matchMedia() is javascript native function.