If I set something in linked JavaScript to be a variable:
color1 = green;
Can I then later call the variable in CSS, like so?
div {
color : color1
}
If I set something in linked JavaScript to be a variable:
color1 = green;
Can I then later call the variable in CSS, like so?
div {
color : color1
}
No, not this way. However if you are interested in using varibales in CSS, you may want to learn LESS, SASS or another CSS preprocessor.
Example:
<h1 style="color:red;" id="red"> I am red </h1>
<script> //JS
document.getElementById("red").setAttribute("style", "color:green;");
</style>
In the above example, JS code selects the element h1
using id and changes it's color to green. So JS is actually altering the inline CSS attribute.
No. CSS can not access Javascript variables.
To use your variable in this way you would assign it to your elements style
property using Javascript. It may look something like this for a single element:
var color1 = 'green',
el = document.getElementById('myDiv')
el.style.color = color1;
<div id="myDiv">Hello</div>
Or this for a number of elements:
var color1 = 'green',
els = document.querySelectorAll('.changeColour')
for (var i = 0; i < els.length; i++) {
els[i].style.color = color1;
}
<div class="changeColour">Hello</div>
<div class="changeColour">Hello</div>