Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery insertAtCaret plugin
// I found this somewhere on the intertubes, and optimized it
$.fn.insertAtCaret = function(myValue) {
return this.each(function() {
var me = this;
if (document.selection) { // IE
me.focus();
sel = document.selection.createRange();
sel.text = myValue;
me.focus();
} else if (me.selectionStart || me.selectionStart == '0') { // Real browsers
var startPos = me.selectionStart, endPos = me.selectionEnd, scrollTop = me.scrollTop;
me.value = me.value.substring(0, startPos) + myValue + me.value.substring(endPos, me.value.length);
me.focus();
me.selectionStart = startPos + myValue.length;
me.selectionEnd = startPos + myValue.length;
me.scrollTop = scrollTop;
} else {
me.value += myValue;
me.focus();
}
});
};
@chrisdpeters

This comment has been minimized.

Copy link

chrisdpeters commented Feb 13, 2013

Thanks for this. This is the only working insertAtCaret implementation that I could find that worked for me.

@houfeng0923

This comment has been minimized.

Copy link

houfeng0923 commented May 18, 2013

//Real broswers .
humor code ..ha

@PhilippePerret

This comment has been minimized.

Copy link

PhilippePerret commented Apr 4, 2019

Maybe:

$.fn.insertAtCaret = function(myValue) {
    if(undefined === myValue || null === myValue){
        // or exception raised
        return
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.