Posted 7 months ago. Visible to the public. Repeats.

How to evaluate CSS media queries in JavaScript

To make CSS rules dependent on the screen size, we use media queries:

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

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() function. It is supported in all browsers and IE11:

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

Detecting when the screen size 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 event, that might call your event listener many times. A better way is to subscribe to changes of the MediaQueryList object that is returned by matchMedia():

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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Henning Koch
Last edit:
7 months ago
by Tobias Kraze
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more