Skip to content Skip to sidebar Skip to footer

How To Prevent Accidental Deletion Of Contenteditable Ul In Ie10?

I want to have a contenteditable ul on a page. However, in Internet Explorer 10, if you click into it, select all with either the right click menu or CTRL+A, then delete, the ul el

Solution 1:

I'd suggest intercepting the delete and backspace keys and doing the delete manually. The steps are:

  • Get the selected range
  • Adjust the ends of the range to lie within the editable <ul> element if they are outside
  • Call deleteContents() on the range.

Note the following won't work on IE <= 8. If you need to support those browsers, you could use my Rangy library, which could also be used to simplify deleteSelectedContent() slightly.

Demo: http://jsfiddle.net/timdown/STcXa/3/

Code:

var editor = document.getElementById("editor");

functiondeleteSelectedContent() {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount > 0) {
            var range = sel.getRangeAt(0);
            var editorRange = range.cloneRange();
            editorRange.selectNodeContents(editor);

            // Adjust selection range boundariesif (range.compareBoundaryPoints(Range.START_TO_START, editorRange) == -1) {
                range.setStart(editorRange.startContainer, editorRange.startOffset);
            }
            if (range.compareBoundaryPoints(Range.END_TO_END, editorRange) == 1) {
                range.setEnd(editorRange.endContainer, editorRange.endOffset);
            }

            range.deleteContents();
        }
    }
}

editor.addEventListener("keydown", function(evt) {
    if (window.getSelection &&
            !window.getSelection().isCollapsed &&
            (evt.keyCode == 8 || evt.keyCode == 46)) {
        evt.preventDefault();
        deleteSelectedContent();
    }
}, false);

Post a Comment for "How To Prevent Accidental Deletion Of Contenteditable Ul In Ie10?"