2

I can get my custom WYSIWYG editor to apply styling to selected text no problem:

pnlDocumentEditor_IFrame.document.execCommand(cmd, ui, opt)

.. but what I need to be able to do is allow the user to set a font, or font size, or bold etc so that text typed AFTER this command is issued will have that style applied.

Is this possible? All execCommands I've tried seem to only work on selected text.

pierre
  • 1,235
  • 1
  • 13
  • 30
  • Did you find a fix for this? Having no selection, how to set multiple formats then type and use those formats? – mircaea May 05 '15 at 15:42
  • I'm afraid not. We went the route of using realobject.com editon-NG editor. Whilst java based, it was the closest at that time I could find to a full Word replacement in-browser. – pierre Sep 07 '15 at 00:40

1 Answers1

0

Appling execCommand on certain element, WITHOUT selecting it with mouse, can be done with this function:

jsFiddle example

function execCommandOnElement(el, commandName, value) {
    if (typeof value == "undefined") {
        value = null;
    }

    if (typeof window.getSelection != "undefined") {
        // Non-IE case
        var sel = window.getSelection();

        // Save the current selection
        var savedRanges = [];
        for (var i = 0, len = sel.rangeCount; i < len; ++i) {
            savedRanges[i] = sel.getRangeAt(i).cloneRange();
        }

        // Temporarily enable designMode so that
        // document.execCommand() will work
        document.designMode = "on";

        // Select the element's content
        sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);

        // Execute the command
        document.execCommand(commandName, false, value);

        // Disable designMode
        document.designMode = "off";

        // Restore the previous selection
        sel = window.getSelection();
        sel.removeAllRanges();
        for (var i = 0, len = savedRanges.length; i < len; ++i) {
            sel.addRange(savedRanges[i]);
        }
    } else if (typeof document.body.createTextRange != "undefined") {
        // IE case
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.execCommand(commandName, false, value);
    }
}

And example usage:

var testDiv = document.getElementById("test");
execCommandOnElement(testDiv, "Bold");
execCommandOnElement(testDiv, "ForeColor", "red");

Source: set execcommand just for a div

Community
  • 1
  • 1
enloz
  • 5,704
  • 9
  • 37
  • 56