Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redefine CSS classes with Javascript

Tags:

javascript

css

Let's say we have defined a CSS class that is being applied to various elements on a page.

colourful
{
    color: #DD00DD;
    background-color: #330033;
}

People have complained about the colour, that they don't like pink/purple. So you want to give them the ability to change the style as they wish, and they can pick their favourite colours. You have a little colour-picker widget that invokes a Javascript function:

function changeColourful(colorRGB, backgroundColorRGB)
{
    // answer goes here
}

What goes in the body of that function?

The intent being that when the user picks a new colour on the colour-picker all the elements with class="colourful" will have their style changed.

like image 934
Axel Avatar asked Nov 05 '08 17:11

Axel


People also ask

Can you change a CSS class with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

Can you manipulate CSS with JavaScript?

Now, JavaScript is a powerful language, so not only can we manipulate HTML elements with it, but we can also use it to manipulate the CSS properties of any webpage.

How do you edit a class in JavaScript?

To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)


2 Answers

var setStyleRule = function(selector, rule) {
    var stylesheet = document.styleSheets[(document.styleSheets.length - 1)];
    if(stylesheet.addRule) {
        stylesheet.addRule(selector, rule)
    } else if(stylesheet.insertRule) {
        stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
    }
};
like image 63
eyelidlessness Avatar answered Oct 13 '22 07:10

eyelidlessness


I would actually implement this server-side; just store the user's preferred colours in their session (via cookies or whatever is nice and easy for you) and generate the CSS dynamically, i.e.

colourful {
  color: ${userPrefs.colourfulColour};
  background-color: ${userPrefs.colourfulBackgroundColour};
} 

If it really suits you much better to do this via Javascript, you can manipulate the CSS using Javascript. See, for instance:

  • Microsoft's Documentation
  • https://developer.mozilla.org/en/DOM/style
like image 30
alex Avatar answered Oct 13 '22 05:10

alex