Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing CSS pseudo-element styles via JavaScript [duplicate]

Is it possible to change a CSS pseudo-element style via JavaScript?

For example, I want to dynamically set the color of the scrollbar like so:

document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color"); 

and I also want to be able to tell the scrollbar to hide like so:

document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden"; 

Both of these scripts, however, return:

Uncaught TypeError: Cannot read property 'style' of null

Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.

like image 838
木川 炎星 Avatar asked Dec 19 '10 03:12

木川 炎星


People also ask

How do you manipulate pseudo elements in JavaScript?

In general, if we want to change anything in pseudo elements through JavaScript, we do it in the following way: Create CSS classes on element, which will change pseudo elements' UI. Get the element using querySelector. Modify the classes using classList.

Can you select pseudo-element in JavaScript?

You can't select pseudo elements in jQuery because they are not part of DOM. But you can add a specific class to the parent element and control its pseudo elements in CSS.

Can JavaScript change HTML styles CSS?

The HTML DOM allows JavaScript to change the style of HTML elements.

Can you have multiple pseudo elements?

1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)


1 Answers

If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.

So in your CSS you can write:

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

Then in your JS you can manipulate that value on the #editor element:

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

Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/

like image 124
Wes Ruvalcaba Avatar answered Sep 25 '22 13:09

Wes Ruvalcaba