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.

2 Responses to Setting Text Selection Colors in JavaScript

  1. Blaise Alicki says:

    It actually works just fine in IE9.

  2. Akshay says:

    It work’s nice. I have an question for you, can you give me solution on this? How can i do four buttons having a name like red, green, blue, orange on selecting any one i get that selection color for the text to get selected.