Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execCommand() doesn't "unbold" text

I made my own WYSIWYG text-editor.

The contenteditable-field is a div, see code below:

<div spellcheck="false" id="textEditorField" contenteditable="true"></div>

The button-events look like this:

boldButton.onclick = function() {
    document.execCommand('bold', false, null); 
    return false; 
}

The texteditor is working fine. It italics and un-italics the text, underlining works. But with bold there is a problem: it bolds the text, but doesn't unbold it. This is in every browser on both OS X and Windows.

I'm using a custom font which is imported using @font-face.

In the css I do the following:

b {
    font-family: "Caviar Dreams Bold";
    font-weight: normal;
}
b i, i b {
    font-family: "Caviar Dreams Bold Italic";
    font-weight: normal;
}

If I remove the font-weight property the text gets the font-family "Caviar Dreams Bold" AND it is made bold via CSS, so extra bold.

There are some similar questions, but without an answer I can use. I also have to note that I can't use jQuery for this.

like image 831
Jeroen Avatar asked Feb 19 '15 19:02

Jeroen


1 Answers

The execCommand('bold'... works as expected, i.e. toggles the surrounding of the text in tag. The problem is that you set 'font-weight: normal' style for the b tag in the following CSS classes. It means that you explicitly want the text in the <b> tag to be normal and it's what you get.

b {
    font-family: "Caviar Dreams Bold";
    font-weight: normal;
}
b i, i b {
    font-family: "Caviar Dreams Bold Italic";
    font-weight: normal;
}

So, you should remove this property and everything work fine.

UPDATE:

It's important to understand how in certain circumstances the method may "bold but not unbold". In fact, execCommand makes something more smart than just surrounding the text. It also normalizes it taking in account that there may be a mix of crossing tags like <b> or <strong> together with <i>, <u>, etc. The browser algorithm analyses the text styles to understand what is actually bold and why. When you redefine bold to normal it may cause the algorithm to decide: "OK, although it's inside <b> tag, the text is not bold and so there is nothing to change" and keeps the tag.

like image 157
Alexander Dayan Avatar answered Oct 02 '22 11:10

Alexander Dayan