views:

135

answers:

4

HI, I'm trying to develop some code in Javascript that adds highlighted text to a class. What I want to achieve with this is the ability of text highlighting with a custom color.

I want it to kind of look like the following:

window.getSelected = "<span class=\"highlighted\">" + window.getSelected + "</span>"

after the above code is executed the selected text's background is surrounded by span tags.

thanks,

fbr

A: 

If you are using the jQuery framework you can try with the following code:

var your_color = 'yellow';
$('.your-class').css('background-color', your_color);

If you're not using it I highly suggest you start; it makes things a lot easier, it's very stable and it's used by many popular websites including google and stack overflow itself.

Andreas Bonini
I've used jQuery... But my question remains unanswered. I'm building an eBook reader with HTML/JAvascript and CSS, and I want to allow users to highlight text. They highlight text with the mouse, pick a color and the selected text's background turns into the color the user picked.
ForeignerBR
A: 

Hello, excuse my english, do you mean adding a class to a text, ok here we go:

function changeClass (elementID, newClass) {
   var element = document.getElementById(elementID);
   element.setAttribute("class", newClass); // This is for good browsers
   element.setAttribute("className", newClass); //For IE
}
leave all lines, its harmless if you do that way. koder.

koder
A: 

If you are talking about styling native selections, use ::selection and ::-moz-selection in CSS.

::selection {
  color: ...;
  background-color: ...;
}

::-moz-selection {
  color: ...;
  background-color: ...;
}

Alternatively, if you want to highlight an arbitrary element with a class:

CSS

.highlighted {
  color: ...;
  background-color: ...;
}

JavaScript

yourElement.className = "highlighted";
Eli Grey
+1  A: 

You'll want to look into Range Objects, there is a good summary here:

http://www.quirksmode.org/dom/range_intro.html

Browser compatibility will be an issue, but basically, you can get the current selection in the way you suggest, then convert it into a Range, and use the methods of the Range object to find and split the existing DOM nodes, and insert your own <span> tag containing the selected text.

It's not entirely trivial, and involves getting into serious DOM manipulation, but it's a rewarding subject to get your head around. Enjoy!

beeglebug