1

Using a selection / key command based WYSIWYG editor. Works great EXCEPT...

With all the other key commands, it toggles the specific style I, strike, etc on and off.

With the execCommand('bold'), it doesn't unbold the text. It's very frustrating. It's the same for every browser.

Here's the code.

$('body').on('keydown', '.element_content, .element_content_subhead', function(e) { 

if(e.ctrlKey){

        //bold -- key 'B'
        if(e.which == 66){
            $sel = $.trim(document.getSelection().toString());
            if($sel == ''){
                alert('Please select some text to bold');
            }
            else{
                document.execCommand('bold', false, null);
            }
        }
       }

});
Mike Reed
  • 74
  • 7
  • Let me add a few things...the using contentEditable
    tags, and for the bold, actually using a stronger typeface in the CSS and not allowing the browser to bold the tag using fong-weight.
    – Mike Reed Jan 09 '14 at 20:16
  • 1
    Nevermind. It was the font-weight:normal !important in the CSS that cause the unbolding error to trigger. – Mike Reed Jan 09 '14 at 20:28

2 Answers2

2

Here's my answer.

Because I was using a non-standard font (ClanWeb), the b to bold the type was not working well for the browsers. So in my CSS I had b{ font-family:ClanWeb-bold; font-weight:normal !important; }

This worked fine for bolding the type, but the execCommand wouldn't fire if the tag didn't behave as normal; didn't have the font-weight:bold in the CSS.

So here was my code to unbold it.

  //bold -- key 'B'
    if(e.which == 66){
        $sel = $.trim(document.getSelection().toString());

        var parentEle = window.getSelection().getRangeAt(0).commonAncestorContainer;
        parentEle = parentEle.parentNode;


        if($sel == ''){
            alert('Please select some text to bold');
        }
        else if(parentEle.tagName == 'B'){
            parentEle.id='unbold1'; 
            $('#unbold1').contents().unwrap();
        }
        else{
            document.execCommand('bold', false, null);
        }
    }
Mike Reed
  • 74
  • 7
  • You can actually use the @font-face property to set the bold version of ClanWeb to be ClanWeb-bold. Then you won't need to set font-weight to normal! http://stackoverflow.com/questions/2436749/how-to-add-multiple-font-files-for-the-same-font – joegoldbeck Dec 01 '15 at 15:31
0

In my case the problem was in 'font: inherit;' bootstrap styles. Summary: if you have problems with 'unbold' or 'unitalic' using document.execComand try to delete all css styles and check your editor - it should work fine after that.

garbo
  • 139
  • 2
  • 2