Getting JavaScript to Talk to CSS and Sass
JavaScript and CSS have been co-existing for more than 20 years, however, sharing data between them has been very difficult. Of course, there have been a lot of attempts, but I came up with a simple and intuitive approach - instead of changing the structure, leveraging CSS custom properties or even Sass variables.
CSS custom properties and JavaScript
The CSS custom properties here shouldn't be too surprising. They have been able to set and manipulate values with JavaScript since browsers began supporting custom properties.
Specifically, we can use JavaScript with custom properties in several ways. We can use setProperty
to set the value of a custom property:
document.documentElement.style.setProperty("--padding", 124 "px"); // 124px
We can also retrieve CSS variables using getComputedStyle
in JavaScript. The logic behind it is quite simple: custom properties are part of the style, so they are also part of the computed style.
getComputedStyle(document.documentElement).getPropertyValue('--padding') // 124px
getPropertyValue
is also a similar way to handle it, which allows us to get custom property values from inline styles of HTML tags.
document.documentElement.style.getPropertyValue("--padding"); // 124px
Note that custom properties are scoped. This means we need to get the computed style from a specific element. Since we defined variables in :root
before, we get them on HTML elements.
Sass variables and JavaScript
Sass is a preprocessing language, which means it is converted to CSS before it becomes part of a website. Therefore, they cannot be accessed from JavaScript like CSS custom properties (accessed as computed styles in the DOM).
We need to modify the build process to change this. I suspect this is not necessary in most cases, as the loader is usually already part of the build process. But if this is not the case with your project, we need three modules that can import and convert Sass modules.
Here is an example in the Webpack configuration:
module.exports = { // ... module: { rules: [ { test: /\.scss$/, use: ["style-loader", "css-loader", "sass-loader"] }, // ... ] } };
In order to make Sass (or more specifically, here SCSS) variables available for JavaScript, we need to "export" them.
// variables.scss $primary-color: #fe4e5e; $background-color: #fefefe; $padding: 124px; :export { primaryColor: $primary-color; backgroundColor: $background-color; padding: $padding; }
:export
block is the magic Webpack uses to import variables. The advantage of this approach is that we can rename the variables using camel nomenclature and select what to disclose.
We then import the Sass file ( variables.scss
) into JavaScript, allowing us to access variables defined in the file.
import variables from './variables.scss'; /* { primaryColor: "#fe4e5e" backgroundColor: "#fefefe" padding: "124px" } */ document.getElementById("app").style.padding = variables.padding;
:export
syntax has some notable limitations:
- It must be at the top level, but can be anywhere in the file.
- If there are multiple in a file, the keys and values are combined and exported together.
- If a
exportedKey
is repeated, the last one (in source order) takes precedence. -
exportedValue
can contain any characters (including spaces) valid in the CSS declaration value. -
exportedValue
does not require quotes, as it is already considered a literal string.
There are many ways to take advantage of accessing Sass variables in JavaScript. I tend to use this method to share breakpoints. Here is my breakpoints.scss
file, which I will import into JavaScript later so that I can get consistent breakpoints using matchMedia()
method.
// Sass variable $breakpoints that define breakpoint value: ( mobile: 375px, tablet: 768px, // etc. ); // Sass variable $media used to write media queries: ( mobile: '(max-width: #{map-get($breakpoints, mobile)})', tablet: '(max-width: #{map-get($breakpoints, tablet)})', // etc. ); // Export module that makes Sass variables accessible in JavaScript: export { breakpointMobile: unquote(map-get($media, mobile)); breakpointTablet: unquote(map-get($media, tablet)); // etc. }
Animation is another use case. The duration of an animation is usually stored in CSS, but more complex animations require the help of JavaScript.
// animation.scss $global-animation-duration: 300ms; $global-animation-easing: ease-in-out; :export { animationDuration: strip-unit($global-animation-duration); animationEasing: $global-animation-easing; }
Note that I used a custom strip-unit
function when exporting variables. This allows me to easily parse content on the JavaScript side.
// main.js document.getElementById('image').animate([ { transform: 'scale(1)', opacity: 1, offset: 0 }, { transform: 'scale(.6)', opacity: .6, offset: 1 } ], { duration: Number(variables.animationDuration), easy: variables.animationEasing, });
I'm happy to be able to exchange data between CSS, Sass and JavaScript so easily. Share variables like this make the code concise and DRY.
Of course, there are many ways to achieve the same function. Les James shared an interesting way to allow Sass and JavaScript to interact over JSON in 2017. I may be biased, but I think the method we're introducing here is the easiest and most intuitive one. It doesn't require crazy changes to the way CSS and JavaScript you've already used and written.
Have you used other methods elsewhere? Please share in the comments – I would love to see how you solved this problem.
The above is the detailed content of Getting JavaScript to Talk to CSS and Sass. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...
