Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yaroslavKas/3817979c7aeb20e18465d6b701b7e272 to your computer and use it in GitHub Desktop.
Save yaroslavKas/3817979c7aeb20e18465d6b701b7e272 to your computer and use it in GitHub Desktop.
js coordinates of bottom text selection
function getSelectionCoords(win) {
win = win || window;
var doc = win.document;
var sel = doc.selection, range, rects, rect;
var x = 0, y = 0;
if (sel) {
if (sel.type != "Control") {
range = sel.createRange();
range.collapse(true);
x = range.boundingLeft;
y = range.boundingTop;
}
} else if (win.getSelection) {
sel = win.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects) {
range.collapse(true);
rects = range.getClientRects();
if (rects.length > 0) {
rect = rects[0];
}
x = rect.left;
y = rect.bottom;
}
if (x == 0 && y == 0) {
var span = doc.createElement("span");
if (span.getClientRects) {
span.appendChild(doc.createTextNode("\u200b"));
range.insertNode(span);
rect = span.getClientRects()[0];
x = rect.left;
y = rect.bottom;
var spanParent = span.parentNode;
spanParent.removeChild(span);
spanParent.normalize();
}
}
}
}
return {x: x, y: y};
}
document.onmouseup = function () {
var coords = getSelectionCoords();
document.getElementById("coords").innerHTML = coords.x + ", " + coords.y;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment