Anna_B
Anna_B

Reputation: 900

Is it possible to change CSS Variables globally via jQuery?

I would like to use CSS Variables and change them globally via jQuery.

Here is some code:

$("div").click(function() {
  // Change globally "--text_color: rgb(0, 0, 255);" to for example "--text_color: rgb(0, 255, 255);"
});
:root {
  --text_color: rgb(0, 0, 255);
}

div {
  color: var(--text_color);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Hello</div>

Is there a way to program this?

Would be very thankful for help!

Upvotes: 1

Views: 966

Answers (4)

Gage
Gage

Reputation: 26

maybe try changing the class via addClass() link

and if you need to change it back you can use removeClass()link

called like this (more or less)

$(document).ready(function(){
  $("button").click(function(){
    $("h1, h2, p").addClass("blue");
    $("div").addClass("important");

with CSS like

.important {
  font-weight: bold;
  font-size: xx-large;
}

.blue {
  color: blue;
}

Upvotes: 1

charlietfl
charlietfl

Reputation: 171690

Append a <style> tag to the head. For further manipulation give it an id so you can easily remove or modify it

const rules = `:root {
  --text_color: rgb(0, 0, 255);}
div {
  color: var(--text_color);
}`


$("div").click(function() {
  $('<style>', {text: rules}).appendTo('head');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Hello</div>

Upvotes: 1

yeho
yeho

Reputation: 144

This has already been asked and answered.

Change CSS variable using jQuery

But to answer your question,

$(this).get(0).style.setProperty(variable, value);

Upvotes: 1

Ibu
Ibu

Reputation: 43850

Since the variable is a global, you can set it anywhere in a style and the value will be updated.

$("div").click(function() {
    this.setAttribute("style", "--text_color: rgb(255, 255, 255);");
});

However, I would suggest you don't modify the global variable but to update a class name instead. Have a list off root variables and use different values in different classes:

:root {
    --text-color1: rgb(0, 0, 255);
    --text-color2: rgb(0, 255, 255);
}
.class1 {
    color: var(--text-color1);
}
.class2 {
    color: var(--text-color1);
}

Now you can change the class name on click:

$("div").click(function() {
   this.className = "class2";
});

Upvotes: 1

Related Questions