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).
cursorActivity
since it triggers on both keyboard and mouse actions.mousedown
, 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?
You could listen to these events:
The cursor was moved by a mouse click if these conditions are met:
cursorActivity
event is triggered after a mousedown
eventvar 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>