How do you format a line of text in a div when clicked?
Using jQuery or straight javascript, how do you define / select / select one line of text from a div with contentEditable and only add formatting to that line of text?
I currently have a div with contentEditable set to true which allows the user to edit the content of the div by adding / removing text as they see fit. However, I want the user to be able to double-click any line of text in the div as well, and mark that line with a different formatting style. (i.e. wrap a full line of text in gaps and then create a range. Note that I can style the range easily. My problem is defining the line of text that the user has clicked and wrapped in span tags)
Note that since the user can add a lot of content, the div itself is scrolling, so any solution should be able to handle scrolling.
a source to share
The jQuery plugin fieldSelection will allow you to get the text selected by the user.
As for wrapping the selected line with a span, the usual jQuery $ () method . wrap () should do the trick.
a source to share
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's a link for more help: https://developer.mozilla.org/en/DOM/range.surroundContents
For IE you can use: You can use the same process in IE using range and selection.
Hope it solves your problem.
a source to share