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.
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.
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)