Home > Web Front-end > JS Tutorial > How to Dynamically Style CSS Pseudo-Elements with JavaScript?

How to Dynamically Style CSS Pseudo-Elements with JavaScript?

Susan Sarandon
Release: 2024-11-15 20:40:02
Original
596 people have browsed it

How to Dynamically Style CSS Pseudo-Elements with JavaScript?

Dynamic CSS Pseudo-Element Styling with JavaScript

Is it feasible to modify CSS pseudo-element styles using JavaScript? For instance, adjusting the scrollbar color dynamically or hiding it. However, attempts to do so with these scripts have resulted in a "TypeError: Cannot read property 'style' of null."

SOLUTION: Introducing CSS Variables

While cross-browser interoperability may not be a priority, using CSS variables (CSS Vars) offers an effective solution in WebKit browsers. This method allows you to declare variables in CSS and dynamically modify them using JavaScript.

In your CSS, define the scrollbar background color as a variable:

#editor {
  --scrollbar-background: #ccc;
}
Copy after login

Then, style the scrollbar thumb using the variable:

#editor::-webkit-scrollbar-thumb:vertical {
  /* Fallback */
  background-color: #ccc;
  /* Dynamic value */
  background-color: var(--scrollbar-background);
}
Copy after login

In JavaScript, you can change the variable value on the #editor element:

document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Copy after login

This approach allows you to modify the scrollbar color dynamically without directly accessing the pseudo-element's style, thus avoiding the "TypeError" issue.

For further examples, refer to this resource on CSS variable manipulation with JavaScript: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/

The above is the detailed content of How to Dynamically Style CSS Pseudo-Elements with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template