Sometimes you want some JS code to execute at certain screen widths, that is, you want different code behavior depending on the viewport width. You also happen to have CSS media queries that modifies the appearance of your website depending on the viewport width.
For example, at viewport widths below 500px, when a user clicks on a button, you want that button to console log a message. But when the viewport width goes above 500px, you want the that same button to alert a message. Why? I don’t know, I can’t think of a better example at the moment.
CSS variables are custom properties that can take in any value that you can then reference in the rest of your CSS, for example:
The trick here is to store every one of your media query values or just the one you want as CSS variables. For the sake of thoroughness, I’ll do the former.
With the help of SCSS, you can store your media query values in a map that you can then loop to store every key/value pair on your document body.
Next, you need to grab the value of the media query you want using the
getComputedStyle method in conjunction with
getPropertyValue. Once you have that value, you can then run code that depends on the size of the viewport width.
In the example below, if the viewport width is below 500px and the user clicks on the click link, then a copy called “mobile” appears. If the viewport width is above 500px and the user clicks on the anchor, “desktop” will appear.