user3143218
user3143218

Reputation: 1816

Creating Pre-Made CSS Variables With JavaScript

Let's say I'm working on a large page. I want to predefine some CSS styles as variables in JavaScript that I can use later. Is it possible? What would the syntax be?

I'm trying to do something like this:

var box = document.querySelector('.box'); 
var styleColor = style.color;
var red = "red"

box.onclick = function(){styleColor.red;}

I'm aware you can do it like this:

var box = document.querySelector('.box');

box.onclick = function(){box.style.color = "red";}

But I want to cache the CSS so It can be re-used later. Is this possible, if so what would the syntax look like?

Upvotes: 0

Views: 34

Answers (1)

Victory
Victory

Reputation: 5890

Write your css in a normal css file. For instance:

.myRedClass { color: red; }

Then append a class to elements you want to be red in javascript as follows

var element = document.getElementById(elementId);
element.className += " " + "myRedClass";

Upvotes: 1

Related Questions