Created
March 4, 2012 17:01
-
-
Save arpit/1973897 to your computer and use it in GitHub Desktop.
Setting the carat in a contentEditable div
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks !
It seems the line "range.selectNodeContents(contentEditableElement);" is not required.