Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS variable using jQuery [duplicate]

Is it possible to change a variable used in CSS using jQuery? Simple example:

html {    --defaultColor: teal;  }  .box {    background: var(--defaultColor);    width: 100px;    height: 100px;    margin: 5px;    float: left;  }  .circle {    background: #eee;    border: 2px solid var(--defaultColor);    width: 100px;    height: 100px;    margin: 5px;    float: left;    border-radius: 100%;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <button id="clickToChange" type="button" style="width: 100%;">Click to Change</button>  <div class="box"></div>  <div class="box"></div>  <div class="box"></div>  <br/>  <div class="circle"></div>  <div class="circle"></div>  <div class="circle"></div>

How can I change the variable color from teal to red for example? This one doesn't work.

$("#clickToChange").click(function(){   $(html).css("--defaultColor", "red"); }); 
like image 919
t4d_ Avatar asked Jun 23 '16 22:06

t4d_


People also ask

How to set CSS Variable in jQuery?

Set a single css variable/property: $(":root"). css("--defaultColor", "red"); . . . or you can Set multiple css variables: $(":root"). css({"--myVar0":myVal0, "--myVar1":myVal1}); , etc... much tidier than non-jQuery solutions IMHO.

How to use clone in jQuery?

jQuery | clone() with Examples The clone() is an inbuilt method in jQuery which is used to make a copy of selected elements including its child nodes, text and attributes. Parameter: It accepts an optional parameter which could be either true or false specifies that event handler should be copied or not.

How to replaceWith in jQuery?

The replaceWith() method in jQuery is used to replace the selected elements with the new one. This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.


1 Answers

You may change the css variable using plain JavaScript elem.style.setProperty("variableName", "variableProp");

$("html").on('click', function() {        $("body").get(0).style.setProperty("--color", "hotpink");      });
body {    --color: blue;    background-color: var(--color);  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    click me!
like image 76
MattDiMu Avatar answered Oct 02 '22 19:10

MattDiMu