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

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/

Leave a Comment