exhtml
4/20/2017 - 5:48 AM

Matching multiple CSS mediaqueries with matchMedia()

Matching multiple CSS mediaqueries with matchMedia()

var mqls = [
	window.matchMedia("(max-width: 1024px)"),
	window.matchMedia("(max-width: 768px)"),
	window.matchMedia("(max-width: 480px)")
]

function cld_media_query_response(mql){

  /* version 1
  Each portion is NOT mutually exclusive, so we DON'T use 'if / else'
  Instead we execute code progressively, 
  and in the end test for when neither queries are matched
  */

  if (mqls[0].matches){
    console.log(mqls[0]);
  }
  if (mqls[1].matches){
    console.log(mqls[1]);
  }
  if (mqls[2].matches){
   console.log(mqls[2]);
  }
  if (!mqls[0].matches && !mqls[1].matches && !mqls[2].matches){
    console.clear();
    console.log('Whatever...');
  }

  /* version 2
  Each portion is mutually exclusive, so we use 'if / else'
  */

  if (/\(max-width:\s*1024px\)/.test(mql.media)){ 
  	console.log(mqls[0]);
  }
  else if (/\(max-width:\s*768px\)/.test(mql.media)){ 
  	console.log(mqls[1]);
  }
  else if (/\(max-width:\s*480px\)/.test(mql.media)){ 
  	console.log(mqls[2]);
  }

}

for (var i=0; i<mqls.length; i++){
  cld_media_query_response(mqls[i]) // call listener function explicitly at run time
  mqls[i].addListener(cld_media_query_response) // attach listener function to listen in on state changes
}