Skip to content

Instantly share code, notes, and snippets.

@arpit
Created March 4, 2012 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save arpit/1973897 to your computer and use it in GitHub Desktop.
Save arpit/1973897 to your computer and use it in GitHub Desktop.
Setting the carat in a contentEditable div
function setCaratTo(contentEditableElement, position)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();
range.selectNodeContents(contentEditableElement);
//range.collapse(true);
range.setStart(contentEditableElement.firstChild, position);
range.setEnd(contentEditableElement.firstChild, position)
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
else if(document.selection)//IE 8 and lower
{
//range = document.body.createTextRange();
//range.moveToElementText(contentEditableElement);
//range.collapse(false);
//range.select();
}
}
@danyboy85
Copy link

Thanks !
It seems the line "range.selectNodeContents(contentEditableElement);" is not required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment