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();
}
}
}
In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document. createRange() method.
createTextRange();//Create a range (a range is a like the selection but invisible) range. moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point.
To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.
There is no fiddle to try but how about placing var tn = ... above first if statement and then use focus() on it, like
var tn = false;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
...
tn = document.createElement("span");
...
}
}
if(clearSelection){
if(sel.toString().length >0){
} else {
/*Do something if the selection length is zero to place the cursor inside the span?*/
if (tn !== false) {
tn.focus();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With