I am working on a function that will style text in a contenteditable div. For example, when Ctrl+b is pressed, <b></b> tags will be inserted around the currently selected text. The problem is that, unlike a textarea, a contenteditable div is not made up of a single text node.
Code:
function moobar(element,e){
if(e.keyCode == "17"){ //IF CTRL IS PRESSED
var selectionStart = window.getSelection().anchorOffset;
var selectionEnd = window.getSelection().focusOffset;
var range = document.createRange(), selection = window.getSelection();
var foobar = document.createElement('div');
if(selectionStart == selectionEnd){
//NO TEXT IS HIGHLIGHTED
//I'LL DEAL WITH THIS PART LATER
} else {
if(selectionStart > selectionEnd){
foobar.innerHTML = element.innerHTML.substring(0, selectionEnd);
element.innerHTML = element.innerHTML.substring(0, selectionEnd) + "<b>" + element.innerHTML.substring(selectionEnd,selectionStart) + "</b>" + element.innerHTML.substring(selectionStart);
} else {
foobar.innerHTML = element.innerHTML.substring(0, selectionStart);
element.innerHTML = element.innerHTML.substring(0, selectionStart) + "<b>" + element.innerHTML.substring(selectionStart,selectionEnd) + "</b>" + element.innerHTML.substring(selectionEnd);
}
range.setStart(element.childNodes[foobar.children.length+2],0);
}
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
}
Might there be a possible way to find out which child of the editable div the offsets are in? For example, if div1's innerHTML was "Some <b>bolded</b> text" and "ex" was highlighted, would there be a way to find out that anchorOffset is inside div1.childNode[2]? If not, then what I really need are just some general suggestions about where to go from here?