Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly repaint array of unicode symbols in JavaScript

I want to change background/foreground color of many symbols with the same CSS class. Right now I'm doing it with jQuery — like $('back_COLORED').css('background-color', '#00FF00'), but this approach is slow when there are many elements with such class (>900).

Seems it's because jQuery don't change CSS rules itself, but finds all elements one-by-one and applies inline styles to them. At least, this is what I see in inspector. So, the question is:

  • How can I change the CSS rules itself?
  • Will it be much faster?
  • Can I make it cross-browser (IE6 doesn't count)?

UPD: I'm trying to make some kind of color scheme editor. The source is at http://github.com/kurokikaze/cinnabar/. Don't mind PHP things, editor is fully client-side (with just some libraries fetched from the net).

UPD2: Tried canvas approach, still slow. Canvas branch is at http://github.com/kurokikaze/cinnabar/tree/canvas.

like image 685
Kuroki Kaze Avatar asked Feb 25 '10 14:02

Kuroki Kaze


2 Answers

The most cross-browser friendly way to override a class definition is to write a new rule and add it to the end of the last stylesheet in the document. You can edit an existing style rule, but even some recent browsers can make it difficult.

function newRule(selector, csstext){
 var SS= document.styleSheets, S= SS[SS.length-1];
 // this example assumes at least one style or link element
 if(S.rules){
  S.addRule(selector,csstext,S.rules.length);
 }
 else if(S.cssRules){
  S.insertRule(selector+'{'+csstext+'}'),S.cssRules.length)
 }
}

newRule('.someclass','background-color:#0f0');

You can add as many 'property:value;' bits in the csstext as you need. Remember to prefix a '.' to a class name or a '#' to an id, and the css must be written as a style rule (with-hyphens, not camelCase).

Of course, it will not override inline styles, and it is overkill for small, local changes. It also may make the redrawing of the page more obvious than changing one element at a time, but it may be just what you need here.

like image 50
kennebec Avatar answered Oct 16 '22 04:10

kennebec


There are different ways depending on which browser you are dealing with. This is documented on Quirks Mode.

Some libraries provide an abstraction layer, such as YUI's StyleSheet utility.

There should be a significant performance boost since you aren't using JS/DOM to cycle through all the elements.

Another approach would be to predefine your styles:

body.foo .myElements { … }

And then edit document.body.className

like image 20
Quentin Avatar answered Oct 16 '22 03:10

Quentin