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

Jitendra Vyas picture Jitendra Vyas · Oct 2, 2011 · Viewed 41k times · Source

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

Answer

Emil Stenström picture Emil Stenström · Oct 3, 2011

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/