The Sex and Cash Theory for Programmers

Insert HTML at Cursor/Caret within a Content Editable Div

27. July 2014 03:29 by Scott in javascript, jquery, C#, Development  //  Tags:   //   Comments (0)

First we need to capture the cursor position within the Div it self.

$scope.editorSelection;

    $scope.SetupEditor = function () {
        var editable = document.getElementById('editor'),
selection, range;
        var captureSelection = function (e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }
            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
            $scope.editorSelection = range;
        };
        editable.onkeyup = captureSelection;
    }

 

From here, we need to be able to insert HTML at the selection when we choose to.

    function insertHtmlAfterSelection(html) {
        var range, expandedSelRange, node;
        if ($scope.editorSelection) {
            range = $scope.editorSelection;
            expandedSelRange = range.cloneRange();
            range.collapse(false);
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    }

 

That will be it.