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

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/


...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;}


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();