Tigran Tigran Tigran Tigran - 4 months ago 52
Javascript Question

textRange MoveToPoint() IE

Have a problem with moveToPoint() method of textRange IE11;

Seems like it dosen't work if pointed node wasn't in first screen;



document.addEventListener( "click", function(e) {
var x = e.clientX;
var y = e.clientY;
var range = document.body.createTextRange();
range.moveToPoint(x, y);
range.expand('word');
console.log(range);
console.log(range.text);
});





This code grab words from click point, but it wokrs normal only if we clicking in node's that were on first scroll.

If we scroll little bit down to the node that wasnt in first scroll, we will catch the exeception.

Does anybody know how to handle this situation correctly?

Answer

I can confirm that such a bug exists in IE11. You can find details here in comments: http://generatedcontent.org/post/69213745095/ie11review-part1

Possible solution (after you create a range):

range.moveToElementText(e.target);
range.collapse(true)
range.expand("word")

Now you have the first word selected. You have to check now if the selected word fits your mouse click position using TextRange properties boundingHeight, boundingWidth, boundingLeft and boundingTop. If it doesn't, you move in cycle to the next word:

range.collapse(false);
range.expand("word");