0

I want to get the position of the selected text inside the textarea. This is necessary in order to show a div with a popup above the selected text. Is there some understandable simple way to calculate this either in vanilla JS or in angular (maybe directive)?

I need coordinates, for setting absolute position

  • https://stackoverflow.com/questions/60359921/how-to-get-highlighted-text-position-from-textarea – Developer Dec 21 '21 at 16:45
  • Or this one: https://stackoverflow.com/questions/59202031/how-to-get-the-screen-coordinates-for-the-selected-text-within-a-textarea – Jean Will Dec 21 '21 at 16:46
  • I need cords. not index @JeanWill –  Dec 21 '21 at 16:52
  • Its not about cords @GaurangDhorda –  Dec 21 '21 at 16:53
  • In the answer of my link, the snippet display absolute position when selection change in the **contenteditable div** not in the textarea. Maybe you could use a contenteditable div instead of a textarea? – Jean Will Dec 21 '21 at 17:00

1 Answers1

2

This is pretty easy to do actually.

You can get the selection start and selection end from any textfield. Take a look at this.

It would work like the following:

document.onselectionchange = function() {
  let inp = document.querySelector("input");

  document.querySelector("p").innerText = "Start: "+inp.selectionStart+"\nEnd: "+inp.selectionEnd+"\n\nSelected: "+inp.value.substring(inp.selectionStart, inp.selectionEnd);
}
<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p></p>
    <input>
  </body>
</html>

If you want to get the position, that doesn't work with inputs for some reason, but here's the code for that too. It grabs the boundingRect from the selection range.

document.onselectionchange = function() {
  let inp = document.querySelector("div");
  let sel = document.getSelection();
  let bound = sel.getRangeAt(0).getBoundingClientRect();

  document.querySelector("p").innerText = "Selected: "+inp.innerText.substring(sel.selectionStart, sel.selectionEnd)+"\n\nX: "+bound.left+"\nY: "+bound.top+"\n\nWidth: "+bound.width+"\nHeight: "+bound.height;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p></p>
    <div style="border: 1px solid black" contenteditable="true">
  </body>
</html>
Battledash2
  • 100
  • 1
  • 8