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: /
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/kthornbloom/RCdhS/
Share Improve this question edited Feb 4, 2013 at 19:10 kthornbloom asked Jan 30, 2013 at 16:56 kthornbloomkthornbloom 3,7403 gold badges32 silver badges47 bronze badges 2- 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 Commented Jan 30, 2013 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 Commented Feb 4, 2013 at 19:11
2 Answers
Reset to default 8You 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/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).monAncestorContainer;
}
} 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;
}
http://jsfiddle/RCdhS/2/
.on('keypress', 'document', function (e) {
if (!$('li').focus();) {
...
}
}
});