Setting Text Selection Colors in JavaScript

If you’re building any kind of a text editor in JavaScript, you might want to be able to dynamically set or change the text selection color. I discovered it wasn’t as easy to do as I expected it to be, so I thought I’d share the code. I created this extreme (and admittedly, somewhat obnoxious) example showing the selection color changing as the mouse moves, but the core of the code is something like this:

var ss = document.styleSheets[0];
ss.insertRule('#content::selection {color: #'+
              newForegroundColor+'; background: #'+
              newBackgroundColor+';}', 0);

Note that I only tested this code in Chrome and Safari (I’m only targeting WebKit browsers for now), however it can work with Firefox with the correct "moz" prefixed style name. I haven’t yet tested or investigated IE.

If you know another way of changing text selection properties in JavaScript, let me know.