2

When I double-click on text with the mouse, the system automatically selects the text for me.

Is there a way to replace this behavior by pressing a hotkey?


I try

<p>Hello world! 123 abc ABC</p>
<script>
  const HOTKEY = "Control"

  let clientX, clientY
  document.addEventListener("mousemove", (e) => {
    clientX = e.clientX
    clientY = e.clientY
  })

  document.addEventListener("keydown", (keyboardEvent) => {
    if (keyboardEvent.key === HOTKEY) {
      const elem = document.elementFromPoint(clientX, clientY)
      console.log(elem)
      elem.dispatchEvent(new MouseEvent("dblclick"))
    }
  })
</script>

It doesn't work.

Expected: For example, If I move the mouse to the world and press the key Ctrl, it should select the text, like below.

enter image description here


Optional reading

In practice, I can't know the actual element.

That is, I can't know through querySelector.

The system generated the element dynamically. The only reliable is to double-click to get the select text.

Carson
  • 6,105
  • 2
  • 37
  • 45
  • Well you would have to figure out _which_ word the mouse cursor is hovering over first of all. And if we are not talking about elements containing only one word each - then you will have to start _calculating_ word positions first ... – CBroe Oct 04 '21 at 10:46

1 Answers1

0

This will select all text in the node, but atleast it works.

<p>Hello world! 123 abc ABC</p>
<script>
  const HOTKEY = "Control"

  let clientX, clientY
  document.addEventListener("mousemove", (e) => {
    clientX = e.clientX
    clientY = e.clientY
  })

  document.addEventListener("keydown", (keyboardEvent) => {
    if (keyboardEvent.key === HOTKEY) {
      const node= document.elementFromPoint(clientX, clientY)

      if (document.body.createTextRange) {
        const range = document.body.createTextRange();
        range.moveToElementText(node);
        range.select();
      } else if (window.getSelection) {
        const selection = window.getSelection();
        const range = document.createRange();
        range.selectNodeContents(node);
        selection.removeAllRanges();
        selection.addRange(range);
      } else {
        console.warn("Could not select text in node: Unsupported browser.");
      }
    }
  })
</script>

Full credit goes to here: Selecting text in an element (akin to highlighting with your mouse)

Jesper
  • 1,007
  • 7
  • 24