If you have the following HTML:
The first paragraph
The second paragraph
>
I think I found a solution.
With the following code snippet you can get the parent element at the current caret position when the selection changes.
var selectedElement = null;
function setFocus(e) {
if (selectedElement)
selectedElement.style.outline = 'none';
selectedElement = window.getSelection().focusNode.parentNode;
// walk up the DOM tree until the parent node is contentEditable
while (selectedElement.parentNode.contentEditable != 'true') {
selectedElement = selectedElement.parentNode;
}
selectedElement.style.outline = '1px solid #f00';
};
document.onkeyup = setFocus;
document.onmouseup = setFocus;
Here I change the outline
property manually but you could of course add a class attribute and set the style via CSS.
You still have to manually check if Here's the updated JSFiddle. EDIT: I updated the code as well as the JSFiddle to make it work in Firefox and Internet Explorer 9+, too. Unfortunately these Browsers do not have a selectedElement
is a child of our contenteditable
attribute. But I think you can get the basic idea.
onselectionchange
event handler, so I had to use onkeyup
and onmouseup
.