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:

// 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
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

Incredible Demos

  • By
    Using Opacity to Show Focus with jQuery

    A few days back I debuted a sweet article that made use of MooTools JavaScript and opacity to show focus on a specified element. Here's how to accomplish that feat using jQuery. The jQuery JavaScript There you have it. Opacity is a very simple but effective...

  • By
    Control Element Outline Position with outline-offset

    I was recently working on a project which featured tables that were keyboard navigable so obviously using cell outlining via traditional tabIndex=0 and element outlines was a big part of allowing the user navigate quickly and intelligently. Unfortunately I ran into a Firefox 3.6 bug...


  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.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!