2

I have working code that inserts <br> when you hit enter in a content editable div. (Browsers have various defaults of inserting <div> or <p> instead)

The problem is that it kills the default behavior of hitting enter to add another list item when building ordered or unordered lists. So my question is, can you detect if the text insertion point is within a list item, and if so, disable the javascript that deals with the enter key?

Working code: http://jsfiddle.net/kthornbloom/RCdhS/

kthornbloom
  • 3,660
  • 2
  • 31
  • 46
  • 2
    Question: Is jQuery available to you? Unsolicited pedantry: You probably either meant "caret" or, more likely, "cursor". EDIT: Never mind. I see that your demo uses jQuery. – isherwood Jan 30 '13 at 17:09
  • Good call, I updated it to say text insertion point since most people probably think of the "cursor" as the arrow you move with your mouse. – kthornbloom Feb 04 '13 at 19:11

2 Answers2

8

You need to do some DOM tree checking on the node containing the selection. Here's a demo that will work in all major browsers:

http://jsfiddle.net/CeMxs/2/

Code:

function isSelectionInsideElement(tagName) {
    var sel, containerNode;
    tagName = tagName.toUpperCase();
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            containerNode = sel.getRangeAt(0).commonAncestorContainer;
        }
    } else if ( (sel = document.selection) && sel.type != "Control" ) {
        containerNode = sel.createRange().parentElement();
    }
    while (containerNode) {
        if (containerNode.nodeType == 1 && containerNode.tagName == tagName) {
            return true;
        }
        containerNode = containerNode.parentNode;
    }
    return false;
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Sorry for the delay in getting back to you. Looks good! I will check it out further and accept the answer if it works out. – kthornbloom Feb 09 '13 at 16:50
  • This does detect if you're inside an
  • . +1 for that! However, I can't get this to work with the existing code in my question above.
  • – kthornbloom Feb 19 '13 at 21:58
  • 1
    Note that this does not work using Chromium v30.0.1599.114 on Xubuntu. In the fiddle, the `alert` dialog prevents the return false from preventing the event to bubble. Removing the `alert` statement resolves the issue. – Dave Jarvis Nov 30 '13 at 05:30
  • @DaveJarvis: Good point. I've added an updated jsFiddle. Thanks. – Tim Down Nov 30 '13 at 10:07