Search code examples
codemirror

How can I get coordsChar to return the correct location?


I'm trying to use coordsChar to get the position of a click in the editor, so that I can then use it to call getTokenAt and detect which word was clicked.

(I'm doing something almost identical to what was described in the following question [codemirror - detect and create links inside editor and was following the suggestions given in the answer there.)

Unfortunately, no matter where I click, coordsChar always returns the location of the end of the document. I think this has something to do with the fact that it always says "outside: true."

How can I get coordsChar to return the correct location?

Here's what I have...

    function onClick (e) {
         if(e.target.className === "cm-myStyle") { 
            //get coords of mouse event
            var x = e.windowX;
            var y = e.windowY;
            var coords = {x,y};

            var loc = editor.coordsChar(coords);

            //this always prints the same location (at the end of the doc)
            console.log(loc);
   }

Solution

  • Update -- got it to work.

    New code:

     function onClick (e) {
         if(e.target.className === "cm-myStyle") { 
            var x = e.pageX;
            var y = e.pageY;
            var coords = {left: x, top: y};
    
            var loc = editor.coordsChar(coords);
    }
    

    I realized I needed to include left: and top: in the coords object. Also, changed windowX and windowY to pageX and pageY.