I've created an editable div and want to change the text inside it, format, and more. However, in doing this, I am using $("#tag").text("aaaaaa")
and when doing this the cursor is moved to the starting position. I need the cursor to be in the final position when edited by .text in jquery.
HTML
<div contenteditable="true" id="tag" name="tag"><span class="spanTag"></div>
JQuery
$("#tag").on('input',function () {
$("#tag").text("asdfasdf");
var range,selection;
if(document.createRange) {
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents($("#tag"));//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
} });