JSFiddle - React, Tailwind, and code Playground
by ecmanaut
HTML
<p>Select something in <b>here</b> using the mouse</p>
<p>Selection top left coordinates: <span id="coords"></span></p>
JavaScript
function getSelectionCoords(win) {
win = win || window;
var doc = win.document;
var sel = doc.selection, range, rects, rect;
var x = 0, y = 0, p = 0;
if (sel) {
if (sel.type != "Control") {
range = sel.createRange();
range.collapse(true);
x = range.boundingLeft;
y = range.boundingTop;
p = 1;
}
} else if (win.getSelection) {
sel = win.getSelection();
p = 2;
if (sel.rangeCount) {
p = 3;
range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects) {
p = 4;
range.collapse(true);
rects = range.getClientRects();
if (rects.length > 0) {
p = 5;
rect = rects[0];
}
x = rect.left;
y = rect.top;
}
// Fall back to inserting a temporary element
if (x == 0 && y == 0) {
var span = doc.createElement("span");
if (span.getClientRects) {
p += 'a';
// Ensure span has dimensions and position by
// adding a zero-width space character
span.appendChild( doc.createTextNode("\u200b") );
range.insertNode(span);
rect = span.getClientRects()[0];
x = rect.left;
y = rect.top;
var spanParent = span.parentNode;
spanParent.removeChild(span);
// Glue any broken text nodes back together
spanParent.normalize();
}
else p += 'b';
}
}
}
return { x: x, y: y, p: p };
}
document.onmouseup = function() {
var coords = getSelectionCoords();
document.getElementById("coords").innerHTML = coords.x + ", " + coords.y + ' - path ' + coords.p;
};