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
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

Incredible Demos

  • By
    Create a Clearable TextBox with the Dojo Toolkit

    Usability is a key feature when creating user interfaces;  it's all in the details.  I was recently using my iPhone and it dawned on my how awesome the "x" icon is in its input elements.  No holding the delete key down.  No pressing it a...

  • By
    jQuery topLink Plugin

    Last week I released a snippet of code for MooTools that allowed you to fade in and out a "to the top" link on any page. Here's how to implement that functionality using jQuery. The XHTML A simple link. The CSS A little CSS for position and style. The jQuery...

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!