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
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos


  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!