Functions document.getSelection() and window.getSelection() do not work in iOS 12.
The problem is reproduced in Safari, Google Chrome and WKWebView.
In iOS 11 and MacOS (any version), these functions are work.
Can you advise?
document.querySelector("#contentjs").onclick = function () { console.log(document.getSelection()); document.querySelector("#result").innerHTML = document.getSelection().anchorOffset; }
Advertisement
Answer
I don’t really know why document.getSelection()
and window.getSelection()
does not work in iOS 12, but the code bellow will return the offset within the node when the user clicks on it.
var contentjs = document.querySelector('#contentjs'); contentjs.onclick = function (e) { var result = document.querySelector('#result'); result.innerHTML = getAnchorOffset(e); }; function getAnchorOffset (event) { var range; if (event.rangeParent && document.createRange) { // Firefox range = document.createRange(); range.setStart(event.rangeParent, event.rangeOffset); range.setEnd(event.rangeParent, event.rangeOffset); return range.startOffset; } else if (document.caretRangeFromPoint) { // Webkit range = document.caretRangeFromPoint(event.clientX, event.clientY); return range.startOffset; } else if (document.caretPositionFromPoint) { // Firefox for events without rangeParent range = document.caretPositionFromPoint(event.clientX, event.clientY); return range.offset; } return 0; }
<h4 id="result">anchorOffset</h4> <div id="contentjs">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>