Aley
Aley

Reputation: 8640

How to unbold text? A tiny WYSIWYG editor

Hey Stackoverflow comunity,

There is a method str.bold() to wrap a text in <b></b> tags. This is just perfect for a tiny WYSIWYG editor (I know some will say I should take one of hundrets open source solutions, but this is for learning purposes too).

The problem is how to unbold the text.

Here is my try http://jsfiddle.net/Kxmaf/178/

I know there is editor.execCommand('bold', false, ''); but this is producing different HTML results on each browser. I need to have only <b></b>, <i></i>, <u></u>

Any help is much appreciated :)

Upvotes: 0

Views: 5044

Answers (2)

Tim Down
Tim Down

Reputation: 324477

You need to consider the case where the user's selection spans paragraphs. For example (selection boundaries indicated with pipes):

<p>One <b>t|wo</b></p>
<p>Thr|ee</p>

To handle this, you need to wrap and all the text nodes and partial text nodes within the user's selection in <b> tags while also detecting which text nodes are already bold and leaving them alone. This is non-trivial, and document.execCommand() handles it all for you, as do the big WYSIWYG editors.

Most browsers allow switching between style modes, allowing you to choose between styling using elements such as <b> and <i> or styling using <span> elements with style attributes. You can do this using the the "StyleWithCSS" command, falling back to "UseCSS" in older browsers. The following switches commands to use the non-CSS version:

try {
    if (!document.execCommand("StyleWithCSS", false, useCss)) {
        // The value required by UseCSS is the inverse of what you'd expect
        document.execCommand("UseCSS", false, !useCss);
    }
} catch (ex) {
    // IE doesn't recognise these commands and throws.
}

Finally, if you switched to using CSS classes instead of <b> etc., you could use the CSS class applier module of my Rangy library.

Upvotes: 2

Alex Cio
Alex Cio

Reputation: 6052

what about looping over a selected string with javascript when pushing the specific style-button. you just could save the several tags like , , .... inside an array, and than loop through the specific string you have selected. so you even can change the style of the style-buttons when any of the tags has been found, to let the user know which style is just used. After deselecting the style just loop again through and delete the tags from string.

Upvotes: 2

Related Questions