I use the setEndOfContenteditable function to put cursor at end of text when making a text-DIV editable.
//Insert cursor at end of contentEditable element
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.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. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
When I used to have only one div, and the text right inside of that, this would work perfectly:
setEndOfContenteditable(curObj);
curObj being the DIV with the text in it.
Now I have switched to a design where I still have the curObj -div but only as a frame, and the DIV that contains the actual text is located inside of that. Normally I do this to reach (select) the inner div in my jQuery code
var curObj = window.curObj;
var inner = '#' + $(curObj).attr("id") + ' .object_inner';
$(inner).doAllMyStuff;
However that doesn't work with this particular setEndOfContenteditable function, the error I get is
Uncaught Error: NotFoundError: DOM Exception 8
and the error points at line 7 of the setEndOfContenteditable function:
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
Ah, I was trying to pass a jQuery selector to a plain javascript function (that expected a raw DOM element). Here is one solution, this gets the raw DOM element:
var spec = $(curObj).find('.object_inner');
setEndOfContenteditable(spec[0]);
Special thanks to this guy: How to get a DOM Element from a JQuery Selector
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.