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
Susan SarandonOriginal
2024-11-15 20:40:02589browse

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;
}

Then, style the scrollbar thumb using the variable:

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

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

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

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!

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