I have a contentditable element. When user selects some text, I know about it using a keyup event. I'm interested in knowing when and if the selection has changed from last selection.
The problem is (see Fiddle):
html:
<div id="div1" contenteditable="true">This is a sample text</div>
js:
$(function(){
var selectedRange, selectedNode;
$("#div1").on("keyup mouseup", function(e) {
selectedRange = window.getSelection().getRangeAt(0);
selectedNode = selectedRange.commonAncestorContainer;
console.log("selected node: ", selectedNode);
console.log("selected node value: ", selectedNode.nodeValue);
console.log("selection chars range: START POS: ", selectedRange.startOffset);
console.log("selection chars range: END POS: ", selectedRange.endOffset);
});
});
When a user selects some text, and then selects another text within the first selection's range (or just puts the caret inside the selected range) - the range object returns the wrong value, claiming that the selection hasn't been changed.
Only after second selection/ mouse click will the range object return the correct value.
It is very important for me to know the selection has changed on the first mouse click.
I came across this answer, 3 years ago, hoping things have changed by now.
Please note I'm supporting all major browsers (ie >=10) (e.g. no "selectstart" event in firefox).
Here's how to reproduce this issue:
- Go to the fiddle attached, run the code and open web console.
- In the output window, select the word "sample" using the mouse, starting from letter "s" , releasing the mouse after letter "e".
- Notice the console saying the start offset ("POS") is 10 & end offset is 16.
- click with the mouse inside the word "sample", between letters "m" to letter "p" (selecting nothing).
- Notice the web console, the range start position & end position are told to stay the same.
- Repeat step 4.
- Notice correct values return by Range API now - position is 13.
Thank you.