I try to create a piece of code in javascript to add a node ("span", "strong"...) in a contenteditable "div" where the caret is (when I click on a "button").
I started thinking about the code like this (it doesn't work, it's just a start): http://jsfiddle.net/Md8KX/2/
HTML:
<div id="myDiv" contenteditable="true">
<strong>Test:</strong> This is a <strong>really</strong> good test.
</div>
<button type="button" id="myButton">Add a span</button>
CSS:
#myDiv{padding:15px;border:solid 1px #000;}
JS:
// Variable to stock the caret position
var caretPosition = 0;
// Event to get caret position on keyup and on blur
$('#myDiv').on('keyup focus', function () {
caretPosition = getCaretPosition(this);
});
// Event to add node when click on button
$('#myButton').on('click', function (e) {
e.preventDefault();
addNode(this, caretPosition, '<span>Node</span>');
});
// Function to get caret position with 1 param : the editable box
var getCaretPosition = function (editableBox) {
var position = 0;
// TO DO : get caret position
return position;
}
// Function to add node with 3 params : the editable box, the caret position and the node to add
var addNode = function (editableBox, caretPosition, nodeToAdd) {
// TO DO : add node in element
}
But I have absolutely no idea to get the cursor position and then insert a node at this point :) I read things about the "range" property in javascript or "createTextRange", but I'm not sure I understand and I don't know if this is the best way to do it.
Have you any idea to do this or a track that could help me to start please? Thank you in advance!