web2.tedsa
web2.tedsa

Reputation: 21

How to change variable :root css by jquery?

How to change variable :root css by jquery?

:root {
      --color: #E72D2D;
}
.box-icon {
    background-color: var(--color);
}

This is not working

    $("#blueColor").click(function(e) {
        $(":root").css("--color", "#137581");
    }

Upvotes: 2

Views: 1843

Answers (3)

Stan Smith
Stan Smith

Reputation: 1

Using CSS variables, I created this code, so I could change the tent of the color by adjusting the H and S variables for an HSL color by changing the CSS via jQuery

CSS:

:root { 
    --H:             90;
    --S:             90%;
    --Main:      hsl( var(--H) var(--S) 50%);
     }

HTML:

<button onclick="color1()">Color #1</button>

Jquery

function color1(){$(':root').css("--H","250").css("--S","50%")};

Upvotes: 0

This working!

$("#blueColor").click(function(e) {
    document.documentElement.style.setProperty('--color', "#137581");
});

or

$("body").get(0).style.setProperty("--color", "#137581");

Upvotes: 1

qwabra
qwabra

Reputation: 2194

<!DOCTYPE html>
<html>
<head lang="ru">
    <meta charset="UTF-8">
    <title>qwabra</title>
    <style>
        * { color: var(--color, black); }
    </style>
    <style id="jqCSS"></style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function(){
    $("#jqCSS").html("");
    function qwa(inch){
        for (var i in inch ) {
            $("#jqCSS").append(i+" {");
                for (var j in inch[i] ) {
                    $("#jqCSS").append(j+":"+inch[i][j]+";");
                };
            $("#jqCSS").append("}");
        };
    };
qwa({ ":root":{"--color":"blue"} });
qwa({ "div":{ "--color": "green"} });
qwa({ "#alert":{ "--color": "red"}, "a":{ "text-decoration":"none" }, "a:hover":{ "text-decoration": "underline" } });
qwa({ "p":{ "background-color": "rgba(128, 128, 128, 0.44);","border": "solid 1px"} });
});
</script>
</head>
<body>


<p>I inherited blue from the root element!</p>
<div>I got green set directly on me!</div>
<div id='alert'>
  While I got red set directly on me!
  <p>I’m red too, because of inheritance!</p>
    <a href="#">href</a>
</div>

</body>
</html>

Upvotes: 0

Related Questions