Home > Software design >  Get position of cursor when highlight the text
Get position of cursor when highlight the text

Time:06-26

I need to create a Chrome Extension which people can use to look up words. And I have found that I use double-click method like when I want to find meaning of a word I just double click and then the notification will appear. (The image below is my Chrome Extension.)

enter image description here.

  • However, I find it is difficult for user to find meaning of pharsal verb, collocation and sentence.
  • So come up with an idea that I can get the position of cursor when user select text and to the last letter of this text I get the position.

enter image description here

  • In addition, I also have found many other Chrome extensions support this feature and they are so great!. One of them is "Edge Translate". When I higlight a text and then I release the mouse it appears a little popup ball then I click to this ball it appears panel. This is their extension: enter image description here

    CodePudding user response:

    To get the text selected you could use this function, then remove the dots, and other characters you are not interested in and split the selected text by spaces to get the last word. (also you don't need the cursor coordinates for it, so you could remove this piece. of the code)

      let hasSelection = false;
      function showCoordsForMouseUp(event) {
          const selection = window.getSelection().toString()
          hasSelection = selection.length;
          if (hasSelection) {
              const x = event.clientX;
              const y = event.clientY;
              const coords = `X coords: ${x} , Y coords: ${y}`;
              console.log(`${coords} - ${selection}`)
          } else {
              console.log('No text selected')
          }
      }
    
      document.onmouseup = showCoordsForMouseUp;
    

    CodePudding user response:

    Thanks for your contribution, I have found the solution with onm ouseUp Event.

    document.onmouseup = function F(e) {
      x = e.pageX;
      y = e.pageY;
      if (window.getSelection().toString() != "") {
        console.log("X: "   x   "Y: "   y);
      }
    }
    <p>
      Flower, flowers.
    </p>

  • Related