Skip to content

Instantly share code, notes, and snippets.

@unicornist
Last active August 30, 2023 01:39
Show Gist options
  • Save unicornist/ac997a15bc3211ba1235 to your computer and use it in GitHub Desktop.
Save unicornist/ac997a15bc3211ba1235 to your computer and use it in GitHub Desktop.
Cross browser caretRangeFromPoint
//demo: http://jsfiddle.net/heZ4z/
if (document.addEventListener) { // standard
document.addEventListener('click', function onclick(e) {
var r;
if (document.caretRangeFromPoint) { // standard (WebKit)
r = document.caretRangeFromPoint(e.pageX, e.pageY);
} else if (e.rangeParent) { // Mozilla
r = document.createRange();
r.setStart(e.rangeParent, e.rangeOffset);
}
var t = r.startContainer; // should be a text node
var s = r.startOffset; // number of chars from the start of text
var e = s;
while (s > 0) {
s -= 1;
r.setStart(t, s);
if (/^\s/.test(r.toString())) {
r.setStart(t, s += 1);
break;
}
}
var l = t.nodeValue.length;
while (e < l) {
e += 1;
r.setEnd(t, e);
if (/\s$/.test(r.toString())) {
r.setEnd(t, e -= 1);
break;
}
}
window.getSelection().addRange(r);
alert(r.toString());
}, false);
} else if (document.attachEvent) { // IE
document.attachEvent('onclick', function onclick(e) {
if (!e) e = window.event;
if (document.selection && document.selection.createRange) {
var r = document.selection.createRange();
r.moveToPoint(e.x, e.y);
r.moveStart('word', -1);
if (/^\s/.test(r.text)) r.moveStart('character', 1);
r.moveEnd('word', 1);
if (/\s$/.test(r.text)) r.moveEnd('character', -1);
r.select();
alert(r.text);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment