Grow your CSS skills. Land your dream job.

Last updated on:

Move Cursor To End of Textarea or Input

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;

  });

};
Check out this Pen!

Reference URL

Comments

  1. I think I’m missing something since it’s behaving exactly like any other input. What’s happening?

  2. Grant
    Permalink to comment#

    Useful for when you have an input or textarea with pre-populated content you wish to preserve. Calling focus will select the existing content, using this plugin will put the cursor at the end, allowing the user to begin typing right away while preserving the content.

  3. Vladimir Minkin
    Permalink to comment#

    Did you test this on mobile web app made with cordova?

  4. Permalink to comment#

    Thank you for this great snippet!
    I had some trouble with appended input elements that could contain a value, since.focus() selects any pre-determined value. This snippet saved me from a lot of extra work.

  5. Hein Haraldson Berg
    Permalink to comment#

    Would it be an idea to cache $(this)?

    Also: Why call it cursor, when what we’re really manipulating is the caret?

  6. Andrey
    Permalink to comment#

    This seems not to work on FF. (I have FF27)

  7. Is it possible using CSS only?

  8. Kerry
    Permalink to comment#

    I’m struggling to implement this behavior on focus of a <textarea>. Has anyone gotten that to work?

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".