views:

245

answers:

3

Using jQuery or straight javascript, how do you identify / select / choose a single line of text from a div with contentEditable on and add formatting to that line of text only?

I currently have a div with contentEditable set to true, which allows the user to edit the content of the div, adding/removing text as they see fit. However, I want the user to also be able to double-click any line of text within the div and mark that line with a different formatting style. (i.e. enclose the full line of text within spans and then style the span. Note that I can style the span easily. My problem lies with identifying the line of text the user clicked and enclosing it in span tags)

Note that since the user can add a lot of content, the div itself is scrollable, so any solution should be able to handle the scrolling.

+1  A: 

The jQuery fieldSelection plugin will allow you to get the text selected by the user.

As far as wrapping the selected line with a span, the usual jQuery $().wrap() method should do the trick.

Jon Dowdle
It seems as if the fieldSelection plugin only works on text fields and text areas. My display area is a div (with contentEditable on)
Snorkpete
Completely forgot that you're using a div when looking for a solution. I think it's worth adding that I've patched a few other jQuery plugins to work in a context that the original author did not intend. This might be an option with the fieldSelect plugin and if you're not finding a solution elsewhere it might be the best bet. If you choose to go that way and want some help let me know.
Jon Dowdle
Duly noted and thanks. I'm not sure if I'll go that route yet, but if I do and need help, I'll be sure to ask.
Snorkpete
A: 

Has anyone ever looked into this a little more, as im trying to get a contenteditable area working with jquery so i can add bold italics links etc to the content editable area via selection of the text!

Wazza
A: 

For Firefox you can use:

// This will give the first selection:
var range = window.getSelection().getRangeAt(0);
var txt = range.toString();
var spn = document.createNode('span');
spn.innerHTML = txt;
// Here you can apply style to spn
range.surrondContents(spn); // It will surround your selected text

Here is the link to get more help: https://developer.mozilla.org/en/DOM/range.surroundContents

For IE you can use: You can use same process in IE too.. using range and selection..

Hope it solves your problem.