views:

36

answers:

1

I have a contenteditable div that I want users to be able to select a portion of, and then click a button to wrap a div with some class and styles around.

The div I want to wrap around:

var newNode = $('<div class=\'selectedFont\' style=\'text-align=center;\'>');

The methods I need to use are in the title, I'm looking for an example.

Thanks.

+1  A: 

My answer to this related question does what you need: http://stackoverflow.com/questions/2887101/apply-style-to-range-of-text-with-javascript-in-uiwebview/2888969#2888969

Tim Down
Thank you. I used your code and it works well. Do you have a method for checking if the selection already has the class applied and doing the removeSpanWithClass onclick rather than applyClassToSelection.
Mark
I'm not quite sure what you mean. It could certainly be improved by adding a check for the each text node in the selection to see if it's already contained within a span of the relevant class to prevent ending up with multiple nested spans with the same class, but I'm not sure that's what you're asking. I am planning to work on this and probably produce a small library, so all suggestions welcome.
Tim Down
Yes that's it. In WYSIWYG editors, if you select a range, the editor checks whether or not it already has various styles applied to it. So if a button applies Style A, and the selected range already has style A, then the button onclick would remove Style A rather than apply it again. A library would be fantastic, thank you so much.
Mark
Ah, that makes sense. I understand now.
Tim Down