search
HomeWeb Front-endCSS TutorialGetting JavaScript to Talk to CSS and Sass

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How much specificity do @rules have, like @keyframes and @media?How much specificity do @rules have, like @keyframes and @media?Apr 18, 2025 am 11:34 AM

I got this question the other day. My first thought is: weird question! Specificity is about selectors, and at-rules are not selectors, so... irrelevant?

Can you nest @media and @support queries?Can you nest @media and @support queries?Apr 18, 2025 am 11:32 AM

Yes, you can, and it doesn't really matter in what order. A CSS preprocessor is not required. It works in regular CSS.

Quick Gulp Cache BustingQuick Gulp Cache BustingApr 18, 2025 am 11:23 AM

You should for sure be setting far-out cache headers on your assets like CSS and JavaScript (and images and fonts and whatever else). That tells the browser

In Search of a Stack That Monitors the Quality and Complexity of CSSIn Search of a Stack That Monitors the Quality and Complexity of CSSApr 18, 2025 am 11:22 AM

Many developers write about how to maintain a CSS codebase, yet not a lot of them write about how they measure the quality of that codebase. Sure, we have

Datalist is for suggesting values without enforcing valuesDatalist is for suggesting values without enforcing valuesApr 18, 2025 am 11:08 AM

Have you ever had a form that needed to accept a short, arbitrary bit of text? Like a name or whatever. That's exactly what is for. There are lots of

Front Conference in ZürichFront Conference in ZürichApr 18, 2025 am 11:03 AM

I'm so excited to be heading to Zürich, Switzerland for Front Conference (Love that name and URL!). I've never been to Switzerland before, so I'm excited

Building a Full-Stack Serverless Application with Cloudflare WorkersBuilding a Full-Stack Serverless Application with Cloudflare WorkersApr 18, 2025 am 10:58 AM

One of my favorite developments in software development has been the advent of serverless. As a developer who has a tendency to get bogged down in the details

Creating Dynamic Routes in a Nuxt ApplicationCreating Dynamic Routes in a Nuxt ApplicationApr 18, 2025 am 10:53 AM

In this post, we’ll be using an ecommerce store demo I built and deployed to Netlify to show how we can make dynamic routes for incoming data. It’s a fairly

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment