1

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!

3

4 Answers 4

1

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";
});
Sign up to request clarification or add additional context in comments.

Comments

1

This has already been asked and answered.

Change CSS variable using jQuery

But to answer your question,

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

Comments

1

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>

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.