JSFiddle - React, Tailwind, and code Playground
by brandonm
HTML
<p>Select something in here using the mouse</p>
<p>Selection top left coordinates: <span id="coords"></span></p>
JavaScript
function getSelectionCoords() {
var sel = document.selection, range;
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 (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects) {
range.collapse(true);
var rect = range.getClientRects()[0];
x = rect.left;
y = rect.top;
}
}
}
return { x: x, y: y };
}
document.onmouseup = function() {
var coords = getSelectionCoords();
document.getElementById("coords").innerHTML = coords.x + ", " + coords.y;
};