Cursor position after mouse click

Hi, I am looking for a way to get the cursor position after a mouse click

The advice in Getting cursor position after mouse click from May '16 seems outdated – I couldn’t find posFromCoords in the docs.

If you’re using version 5, you want coordsChar.

Hi, I’m using version 6, What would be the right way to get the cursor position after mouse click for that?

posAtCoords is the method for that in version 6.

I’ve been able to get the screen coordinates of mouse clicks:

editorNode.onclick = (event) => { console.log('1. clicked', event.clientX, event.clientY); };

Am now trying to translate them into cursor position using posAtCoords as you suggested. But I can’t figure out how to call that function. My various tries:

function positionAtEvent(event){
   // UNDEFINED: editor.posAtCoords({x: event.clientX, y: event.clientY})
   // POSATCOORDS UNDEFINED: posAtCoords({x: event.clientX, y: event.clientY})     
   // NOT A FUNCTION: EditorView.posAtCoords({x: event.clientX, y: event.clientY})

This above code occurs in a context in which editor is defined:

let editor = new EditorView({
      state: EditorState.create({ ...

Thanks again for your help.

This sounds like a confusion about basic JavaScript concepts, which is beyond the scope of this forum.

OK, thanks!

re: posAtCoords:

A more precise question. Looking through the codemirror 6 source code, I found

    export function posAtCoords ...

in view/src/cursor.ts of

Then I modified my imports so as to have

    import {EditorView, keymap, posAtCoords} from "@codemirror/view"

However, when I run npm start, I get a “non-existent import error” regarding posAtCoords (see attached). Should I be importing from somewhere else?


(base) ➜  editor-prepare git:(cm6) ✗ npm start

> codemirror@1.0.0 start
> rollup -c

./editor.js → ./editor.bundle.js...
(!) Import of non-existent export
6: import {EditorState,basicSetup} from "@codemirror/basic-setup"
7: import {EditorView, keymap, posAtCoords} from "@codemirror/view"
8: // import {search} from "@codemirror/search"
9: import {indentWithTab} from "@codemirror/commands"
created ./editor.bundle.js in 575ms

NB. In my package.json: "@codemirror/view": "^0.19.0". Also, I find the text

function posAtCoords(view, { x, y }, precise, bias = -1) { ..

in my node_modules/@codemirror/view/dist/index.js.

This is the kind of question that the docs can answer for you. It’s a method on EditorView.

Thanks very much, and thanks for your patience. All working now!