2

Good day,

I am working with CSS3 variables to offset items and many other things in runtime however JQuery's css method ignores any attempt at setting a css var. I try the following

    $(document).ready(function() {
        $('#testdiv').css('--bgc','rgb(0,0,255)');
    });
 div
    {
        --bgc:rgb(255,0,0);
        background-color:var(--bgc);
        width:50px;
        height:50px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="testdiv"></div>

So in theory the div should initially load as a 50px by 50px red box and as soon as page loading is complete change into a blue box however the --bgc variable is never changed on the DIV. Is there any way to set this in JQuery?

6
  • @AnujKumar read the title Commented Jul 14, 2016 at 12:30
  • @AnujKumar that is a css variable, see the css class added in the post. Commented Jul 14, 2016 at 12:31
  • @UgoT. Read the title and use Goog Commented Jul 14, 2016 at 12:31
  • I ask because I never heard of it. Try background-color instead. Commented Jul 14, 2016 at 12:32
  • try as attribute $('#testdiv').attr("style","--bgc:rgb(0,0,255)"); Commented Jul 14, 2016 at 12:35

2 Answers 2

4

I found a pure JavaScript solution:

JS:

$(document).ready(function() {
    document.documentElement.style.setProperty('--bgc', 'rgb(0,0,255)');
});

CSS:

:root {
    --bgc: rgb(255,0,0);
}

div {
    background-color:var(--bgc);
    width:50px;
    height:50px;
}

Codepen: http://codepen.io/theblindprophet/pen/yJpZNb

Reference: Variables why should you care?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that seems to work, I wanted to be able to set it on JQuery collections but I gues $().each() will have to do
0

You can set variable via vanilla javascript

$(document).ready(function() {
  $('#testdiv')[0].style.setProperty('--bgc', 'rgb(0, 0,255)');
});

$(document).ready(function() {
  $('#testdiv')[0].style.setProperty('--bgc', 'rgb(0,0,255)');
});
div
{
    --bgc:rgb(255,0,0);
    background-color:var(--bgc);
    width:50px;
    height:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testdiv"></div>

6 Comments

where is vanilla javascript in your answer?
$('#testdiv') doesn't return an array. You shouldn't need the [0]
@Jai here: .style.setProperty() @theblindprophet try it without the [0]
@user1636505 yet that is not vanilla javascript. You are still in jquery and you are converting a jq object to the dom node.
@Jai I've used jQuery so that OP can see the diff
|

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.