I have a contenteditable div that has formatting options. I would like to be able to click on, say the bold button, and insert <span class="bold">
and </span>
to the left and right of my cursor respectively. I believe I have managed to do this. However, I do not know how to place the cursor inside the span so that the user might start typing in bold text.
The function I am currently working with:
function bold(text,clearSelection) {
text = text.replace(/\r\n/g,"<br>");
var sel, range, html;
var tn = false;
//Here i am adding the span element
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
tn = document.createElement("span");
tn.className="bold";
tn.innerHTML=text;
range.insertNode(tn);
}
}
if(clearSelection){
//if the selection length is longer than 0, move cursor to end of selection
if(sel.toString().length >0){
range = window.getSelection().getRangeAt(0);
range.setStart(range.endContainer,range.endOffset);
document.getElementById('text').focus();
} else {
/*Do something if the selection length is zero to place the cursor inside the span?*/
}
}
}
Edit: The following ended up working
if(clearSelection){
//if the selection length is longer than 0, move cursor to end of selection
if(sel.toString().length >0){
range = window.getSelection().getRangeAt(0);
range.setStart(range.endContainer,range.endOffset);
document.getElementById('text').focus();
} else {
if(tn!==false){
range.selectNodeContents(tn);
document.getElementById('text').focus();
}
}
}