48

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

Jitendra Vyas
  • 148,487
  • 229
  • 573
  • 852
  • Why would you want jQuery to only run on one size and orientation? – Eric Oct 02 '11 at 10:15
  • What do you want to happen if the orientation or size changes after loading? (device rotated, window resized, etc) – Eric Oct 02 '11 at 10:17
  • i want to use a image resize jquery plugin only if max-width:1025px and max-width:2048px – Jitendra Vyas Oct 02 '11 at 10:18
  • You should include the library no matter what. Just don't use the functions unless the screen is of the correct size – Eric Oct 02 '11 at 10:20
  • @Eric - this is the plugin which I want to use to image re-sizing http://www.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. http://stackoverflow.com/questions/7613810/what-is-this-technique-to-resize-the-images-proportionally-used-by-google-chrome – Jitendra Vyas Oct 02 '11 at 10:25
  • 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. – Eric Oct 02 '11 at 10:29
  • @Jitendra: Here's a better way to resize images for mobile phones: http://www.sencha.com/learn/how-to-use-src-sencha-io/ – Emil Stenström Oct 12 '11 at 08:01
  • 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. – rlcrews Oct 23 '12 at 14:16
  • @JitendraVyas: Would you mind marking my answer as accepted? It has 42 votes, so I think it should be considered the best one. – Emil Stenström Jul 27 '15 at 10:13

6 Answers6

66

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/

ludovico
  • 2,103
  • 1
  • 13
  • 32
Emil Stenström
  • 13,329
  • 8
  • 53
  • 75
  • 3
    There is a video from Google that explain That : http://youtu.be/svEg7MiqGf8?t=3m4s – Yoann Oct 11 '11 at 15:25
  • 2
    I think [`matchMedia()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) is javascript native function. – Mohammad Oct 09 '18 at 10:16
12

...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;
}
mowwwalker
  • 16,634
  • 25
  • 104
  • 157
11

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();
Eric
  • 95,302
  • 53
  • 242
  • 374
  • 1
    +1 Just finished typing a similar answer, but you were faster. – Rob W Oct 02 '11 at 10:12
  • That's what I said, but I think the problem is that the CSS executes instantly based on this example: http://www.1stwebdesigner.com/css/how-to-use-css3-orientation-media-queries/ Which would mean that it wouldn't be instant and you would have to keep checking. – mowwwalker Oct 02 '11 at 10:12
  • I guess my answer is just invisible? – mowwwalker Oct 02 '11 at 10:13
  • @Walkerneo: CSS executing instantly is good! That'd make it happen before the javascript! As for your answer, it's just too vague. – Eric Oct 02 '11 at 10:14
  • @Walkerneo - you are right. I want to run a javascript only if max-width of browser is 1900px and min-width is 768. – Jitendra Vyas Oct 02 '11 at 10:15
  • 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. – mowwwalker Oct 02 '11 at 10:15
  • This means you have to select a random element and change its style to execute some javascript. Doesn't seem like a good idea... – Emil Stenström Oct 02 '11 at 10:15
  • @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. – Eric Oct 02 '11 at 10:16
  • @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 – mowwwalker Oct 02 '11 at 10:17
  • @Eric - Can you please answer of this question http://stackoverflow.com/questions/7613810/what-is-this-technique-to-resize-the-images-proportionally-used-by-google-chrome 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 – Jitendra Vyas Oct 02 '11 at 10:36
  • What do you want to happen if they're not on a mobile device? – mowwwalker Oct 02 '11 at 10:44
  • @Walkerneo - on mobile device I would not re-size the picture. So i will not need any javascript condition – Jitendra Vyas Oct 02 '11 at 10:48
  • @JitendraVyas, but your example code checks for window orientation, which only exists in mobile devices... – mowwwalker Oct 02 '11 at 10:50
  • @Walkerneo - yes I'm considering iPad but not iphone – Jitendra Vyas Oct 02 '11 at 10:51
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/3961/discussion-between-jitendra-vyas-and-walkerneo) – Jitendra Vyas Oct 02 '11 at 10:51
0

It's probably worth mentioning that there is the orientationchange event that you might want to hook into like so:

$('body').bind('orientationchange', function(){
    // check orientation, update styles accordingly
});

I know that about this event being fired by mobile Safari, you'd have to check about other browsers.

vzwick
  • 11,008
  • 5
  • 43
  • 63
0

You could just rewrite the media query as a javascript expression instead:

function sizehandler(evt) {
    ...
}

function orientationhandler(evt){  

  // For FF3.6+  
  if (!evt.gamma && !evt.beta) {  
    evt.gamma = -(evt.x * (180 / Math.PI));  
    evt.beta = -(evt.y * (180 / Math.PI));  
  }  

  // use evt.gamma, evt.beta, and evt.alpha   
  // according to dev.w3.org/geo/api/spec-source-orientation  

  ...
}  

window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
window.addEventListener('load', orientationhandler, false); 
window.addEventListener('resize', sizehandler, false); 
window.addEventListener('load', sizehandler, false); 
Emil Stenström
  • 13,329
  • 8
  • 53
  • 75
-1

The simplest way I found is to get the width of our page; then to conditionally use it.

var x = document.documentElement.clientWidth;
if (x < 992) {     
        document.body.style.backgroundColor = "yellow";
}
crg
  • 4,284
  • 2
  • 29
  • 57