Oak Oak - 1 year ago 58
Javascript Question

How can I act on cursor activity originating from mouse clicks and not keyboard actions?

I want to do something when a user moves the cursor to another location via a mouse click, but not do it when it's done via a keyboard action (arrows, pageup/pagedown, home/end).

  • I can't just listen to
    since it triggers on both keyboard and mouse actions.

  • I'm not sure I can listen to
    , because it might be the start of something which is not a cursor location change (e.g. selecting, dragging).

What's the best way to catch those mouse-originated cursor movements?

Answer Source

You could listen to these events:

  • mousedown
  • cursorActivity
  • keydown
  • beforeChange

The cursor was moved by a mouse click if these conditions are met:

  • A cursorActivity event is triggered after a mousedown event
  • No movement key was pressed between the two events
  • No change was made to the content between the two events
  • No text is selected

var movedByMouse = false;

var editor = CodeMirror(document.body);

editor.on("mousedown", function () {
    movedByMouse = true;

editor.on("cursorActivity", function () {
    if (movedByMouse) {
        movedByMouse = false;
        if (!editor.getSelection()) {
            console.log("Moved by mouse");

editor.on("keydown", function () {
    if (isMovementKey(event.which)) {
        movedByMouse = false;

editor.on("beforeChange", function () {
    movedByMouse = false;

function isMovementKey(keyCode) {
    return 33 <= keyCode && keyCode <= 40;
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.20.2/codemirror.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.20.2/codemirror.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download