Getting JavaScript to Speak to CSS and Sass

JavaScript and CSS have lived beside each other for upwards of 20 years. And but it’s been remarkably powerful to share knowledge between them. There have been massive makes an attempt, positive. However, I’ve one thing easy and intuitive in thoughts — one thing not involving a structural change, however fairly placing CSS customized properties and even Sass variables to make use of.

CSS customized properties and JavaScript

Customized properties shouldn’t be all that shocking right here. One factor they’ve all the time been capable of do since browsers began supporting them is figure alongside JavaScript to set and manipulate the values.

Particularly, although, we are able to use JavaScript with customized properties in a couple of methods. We will set the worth of a customized property utilizing setProperty:

doc.documentElement.fashion.setProperty(“–padding”, 124 + “px”); // 124px

We will additionally retrieve CSS variables utilizing getComputedStyle in JavaScript. The logic behind that is pretty easy: customized properties are a part of the fashion, subsequently, they’re a part of computed fashion.

getComputedStyle(doc.documentElement).getPropertyValue(‘–padding’) // 124px

Similar kind of take care of getPropertyValue. That permit us get the customized property worth from an inlined fashion from HTML markup.

doc.documentElement.fashion.getPropertyValue(“–padding'”); // 124px

Be aware that customized properties are scoped. This implies we have to get computed kinds from a specific aspect. As we beforehand outlined our variable in :root we get them on the HTML aspect.

Sass variables and JavaScript

Sass is a pre-processing language, that means it’s was CSS earlier than it ever is part of a web site. For that cause, accessing them from JavaScript in the identical manner as CSS customized properties — that are accessible within the DOM as computed kinds — just isn’t potential. 

We have to modify our construct course of to vary this. I doubt there isn’t an enormous want for this typically since loaders are sometimes already a part of a construct course of. But when that’s not the case in your venture, we want three modules which can be able to importing and translating Sass modules.

Right here’s how that appears in a webpack configuration:

module.exports = ;

To make Sass (or, particularly, SCSS on this case) variables out there to JavaScript, we have to “export” them.

// variables.scss
$primary-color: #fe4e5e;
$background-color: #fefefe;
$padding: 124px;

:export
  primaryColor: $primary-color;
  backgroundColor: $background-color;
  padding: $padding;

The :export block is the magic sauce webpack makes use of to import the variables. What is good about this strategy is that we are able to rename the variables utilizing camelCase syntax and select what we expose.

Then we import the Sass file (variables.scss) file into JavaScript, giving us entry to the variables outlined within the file.

import variables from ‘./variables.scss’;

/*
 
*/

doc.getElementById(“app”).fashion.padding = variables.padding;

There are some restrictions on the :export syntax which can be price calling out:

It have to be on the high stage however might be wherever within the file.If there may be a couple of in a file, the keys and values are mixed and exported collectively.If a specific exportedKey is duplicated, the final one (within the supply order) takes priority.An exportedValue could include any character that’s legitimate in CSS declaration values (together with areas).An exportedValue doesn’t must be quoted as a result of it’s already handled as a literal string.

There are many methods getting access to Sass variables in JavaScript can turn out to be useful. I have a tendency to achieve for this strategy for sharing breakpoints. Right here is my breakpoints.scs file, which I later import in JavaScript so I can use the matchMedia() technique to have constant breakpoints.

// Sass variables that outline breakpoint values
$breakpoints: (
  cell: 375px,
  pill: 768px,
  // and many others.
);

// Sass variables for writing out media queries
$media: (
  cell: ‘(max-width: #map-get($breakpoints, cell))’,
  pill: ‘(max-width: #)’,
  // and many others.
);

// The export module that makes Sass variables accessible in JavaScript
:export

Animations are one other use case. The period of an animation is normally saved in CSS, however extra advanced animations must be executed with JavaScript’s assist.

// animation.scss
$global-animation-duration: 300ms;
$global-animation-easing: ease-in-out;

:export
  animationDuration: strip-unit($global-animation-duration);
  animationEasing: $global-animation-easing;

Discover that I take advantage of a customized strip-unit operate when exporting the variable. This enables me to simply parse issues on the JavaScript facet.

// most important.js
doc.getElementById(‘picture’).animate([
  transform: ‘scale(1)’, opacity: 1, offset: 0 ,
 
], );

It makes me completely satisfied that I can trade knowledge between CSS, Sass and JavaScript so simply. Sharing variables like this makes code easy and DRY.

There are a number of methods to realize the identical kind of factor, after all. Les James shared an attention-grabbing strategy in 2017 that permits Sass and JavaScript to work together by way of JSON. I could also be biased, however I discover the strategy we lined right here to be the only and most intuitive. It doesn’t require loopy modifications to the best way you already use and write CSS and JavaScript.

Are there different approaches that you just is likely to be utilizing someplace? Share them right here within the feedback — I’d like to see the way you’re fixing it.

Leave a Reply