CodeMirror: Set Focus at End of Line

By  on  

CodeMirror is a WYSIWYG-like editor that allows for rich text editing on a small scale, oftentimes used to allow Markdown editing, much like ReviewBoard uses it for.  One problem I've found, however, is that calling a CodeMirror instance's focus method put the cursor at the beginning of the input, which is annoying when there is input in the field.  In theory you'd always want to put the cursor at the end so that the user can continue adding to the text that's already there.

Here's a snippet that will set the cursor to the end of existing input:

cmInstance.focus();
// Set the cursor at the end of existing content
cmInstance.setCursor(cmInstance.lineCount(), 0);

You would think that there would be a method which would accomplish this task, or even have focus set the cursor to the end of input by default if the instance has existing text.  Anyways, this is the code that will put the cursor at the end of your CodeMirror input instance!

Recent Features

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

Incredible Demos

  • By
    MooTools History Plugin

    One of the reasons I love AJAX technology so much is because it allows us to avoid unnecessary page loads.  Why download the header, footer, and other static data multiple times if that specific data never changes?  It's a waste of time, processing, and bandwidth.  Unfortunately...

  • By
    Skype-Style Buttons Using MooTools

    A few weeks back, jQuery expert Janko Jovanovic dropped a sweet tutorial showing you how to create a Skype-like button using jQuery. I was impressed by Janko's article so I decided to port the effect to MooTools. The XHTML This is the exact code provided by...

Discussion

  1. Harika

    HI David,

    I was able to set cursor at end of the code mirror lines on tab with your code, but after that i want to get out of code mirror window and should move focus to next button.With above code, not able to get focus out of code mirror, can you suggest a way to do that? Thanks.

    This is how i am writing it, also set tabindex=0 for next button available.

     _editor.setOption('extraKeys', {
            Tab(cm) {
              cm.focus();
              cm.setCursor(cm.lineCount(), 0);
            },
          });

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!