Skip to content

Instantly share code, notes, and snippets.

@06b
Created March 14, 2013 17:55
Show Gist options
  • Save 06b/5163552 to your computer and use it in GitHub Desktop.
Save 06b/5163552 to your computer and use it in GitHub Desktop.
Put the cursor at the end of a textbox
// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea
// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
jQuery.fn.putCursorAtEnd = function()
{
return this.each(function()
{
$(this).focus()
// If this function exists...
if (this.setSelectionRange)
{
// ... then use it
// (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
}
else
{
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
})(jQuery);
@daverogers
Copy link

It would be cool if this were a micro-repo that could be more easily distributed via Bower.

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