Read more

How to evaluate CSS media queries in JavaScript

Henning Koch
May 11, 2020Software engineer at makandra GmbH

To make CSS rules dependent on the screen size, we use media queries Show archive.org snapshot :

@media (max-width: 500px) {
  // rules for screen widths of 500px or smaller
}
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Browsers will automatically enable and disable the conditional rules as the screen width changes.

To detect responsive breakpoints from JavaScript, you may use the global matchMedia() Show archive.org snapshot function. It is supported in all browsers and IE11:

let query = window.matchMedia('(max-width: 500px)')
query.matches // => true or false

Detecting when the query result changes

The #matches() method tests the current screen width. To be notified when the width changes, you need additional scripting.

While you may bind to the window's resize Show archive.org snapshot event, that might call your event listener many times. A better way is to subscribe to changes of the MediaQueryList Show archive.org snapshot object that is returned by matchMedia():

let query = window.matchMedia('(max-width: 500px)')
query.addEventListener('change', function(event) {
  query.matches // => true or false  
})

If you want to know the current breakpoint tier (in Bootstrap e.g. "xs" or "md") without duplicating breakpoints to JavaScript: you can read the current breakpoint tier(s) in JavaScript.

Posted by Henning Koch to makandra dev (2020-05-11 08:58)