Created
December 14, 2012 11:21
-
-
Save stryju/4284734 to your computer and use it in GitHub Desktop.
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 caretInception( node, index, found ){ | |
var response = { | |
found : found, | |
index : index | |
}; | |
if ( found ) { | |
return response; | |
} | |
// if textNode - do magic | |
if ( node.nodeType === 3 ) { | |
if ( node.textContent.length >= index ) { | |
response.found = node; | |
} else { | |
response.index -= node.textContent.length; | |
} | |
return response; | |
} | |
// if not textNode - make childNodes do the magic for you | |
var child_response; | |
$.each( node.childNodes, function( child_node_index, child_node ){ | |
if ( ! response.found ){ | |
child_response = caretInception( child_node, response.index ); | |
response.index = child_response.index; | |
if ( child_response.found ) { | |
response = child_response; | |
} | |
} | |
}); | |
return response; | |
} | |
function setCaret( el, index ){ | |
if ( window.getSelection ){ | |
var sel = window.getSelection(); | |
sel.removeAllRanges(); | |
var range = document.createRange(); | |
range.selectNodeContents( el ); | |
// http://inception.davepedu.com | |
var brrrrrrraaaaawwwwrwrrrmrmrmmrmrmmmmm = caretInception( el, index ); | |
range.setStart( brrrrrrraaaaawwwwrwrrrmrmrmmrmrmmmmm.found , brrrrrrraaaaawwwwrwrrrmrmrmmrmrmmmmm.index ); | |
range.collapse( true ); | |
sel.addRange( range ); | |
} | |
} | |
function getCaret( el ){ | |
var pos = 0; | |
if ( window.getSelection ){ | |
if ( ! window.getSelection().rangeCount ){ | |
return $( el ).text().length; | |
} | |
var range = window.getSelection().getRangeAt( 0 ); | |
var preCaretRange = range.cloneRange(); | |
preCaretRange.selectNodeContents( el ); | |
preCaretRange.setEnd( range.endContainer, range.endOffset ); | |
pos = preCaretRange.toString().length; | |
} | |
return pos; | |
} | |
function getCaretPosition( el, offset_top ){ | |
var range = window.getSelection().getRangeAt( 0 ); | |
var node = document.createElement( 'b' ); | |
range.insertNode( node ); | |
var $node = $( node ); | |
var pos = $node.position(); | |
if ( offset_top ){ | |
pos.top += $node.height(); | |
} | |
$node.remove(); | |
return pos; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment