user1145643 February 2016

Javascript WYSIWYG Logic

I've searched SO for similar questions, but it seems that they are all wrapped up in just making a div editable using contenteditable="true".

I am curious about the most efficient way to keep track of all the formatting tags added to a document. Just wrapping / unwrapping selected text with jQuery seems to corrupt the document after a few edits because of broken overlapping tags.

Would the correct approach be to separate all characters into an array, work out a logic to add / modify / remove tags at positions defined by window.getSelection(), and then render an output version to load into the editable div? Or is there a better solution?

Answers


user1145643 February 2016

It may be unnecessary to wrap elements in tags manually with javascript / jquery. I've been reading about execCommand() and it seems to be widely supported. This would allow for most formatting options found in WYSIWYG editors, color, font size, family, adding links, etc... I realize that my initial question was a little broad, but perhaps this will point someone else in the right direction as well...

Examples:

document.execCommand('bold', 0);
document.execCommand('forecolor', 0, '#ff0000');
document.execCommand('fontSize', 0, '7');

Works in chrome / firefox / safari, not sure about IE yet. The above bold example demonstrates how the browser keeps track of the existing formatting and can toggle the style on/off.

Post Status

Asked in February 2016
Viewed 2,460 times
Voted 13
Answered 1 times

Search




Leave an answer