Skip to content

Instantly share code, notes, and snippets.

@junaidpv
Created July 31, 2011 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junaidpv/1117113 to your computer and use it in GitHub Desktop.
Save junaidpv/1117113 to your computer and use it in GitHub Desktop.
Example for proper text replacement.
--- Base (BASE)
+++ Locally Modified (Based On LOCAL)
@@ -150,7 +150,54 @@
$element.removeClass( 'narayam-input' );
}
}
+ /**
+ * from: http://stackoverflow.com/questions/3274843/get-caret-position-in-textarea-ie
+ */
+ function offsetToRangeCharacterMove(el, offset) {
+ return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
+ }
+ /**
+ * IE part from: http://stackoverflow.com/questions/3274843/get-caret-position-in-textarea-ie
+ */
+ function setCaretPosition (el, iCaretPos)
+ {
+ if (document.selection) // IE
+ {
+ endOffset = startOffset=iCaretPos;
+ var range = el.createTextRange();
+ var startCharMove = offsetToRangeCharacterMove(el, startOffset);
+ range.collapse(true);
+ if (startOffset == endOffset) {
+ range.move("character", startCharMove);
+ } else {
+ range.moveEnd("character", offsetToRangeCharacterMove(el, endOffset));
+ range.moveStart("character", startCharMove);
+ }
+ range.select();
+ }
+ else if (el.selectionStart || el.selectionStart == '0') // Firefox
+ {
+ el.setSelectionRange(iCaretPos, iCaretPos)
+ }
+ }
+ function replaceAt( $element, start, end, replacement )
+ {
+ var newCaretPosition;
+ var text = $element.val();
+ if ( text.length == 0 ) {
+ $element.val( replacement );
+ newCaretPosition = replacement.length;
+ } else {
+ var firstString = text.substring( 0, start );
+ var lastString = text.substring( end, text.length );
+ $element.val( firstString + replacement + lastString );
+ newCaretPosition = firstString.length + replacement.length;
+ }
+
+ setCaretPosition($element.get(0), newCaretPosition);
+ }
+
/**
* Keydown event handler. Handles shortcut key presses
* @param e Event object
@@ -224,15 +271,7 @@
replacement = replacement.substring( divergingPos );
// Select and replace the text
- $this.textSelection( 'setSelection', {
- 'start': startPos - input.length + 1,
- 'end': endPos
- } );
- $this.textSelection( 'encapsulateSelection', {
- 'peri': replacement,
- 'replace': true,
- 'selectPeri': false
- } );
+ replaceAt($this, startPos- input.length + 1, endPos, replacement);
e.stopPropagation();
return false;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment