Created
November 13, 2015 09:55
-
-
Save dmy3k/a3b72c274d41e489e063 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.top; | |
} | |
// Fall back to inserting a temporary element | |
if (x == 0 && y == 0) { | |
var span = doc.createElement("span"); | |
if (span.getClientRects) { | |
// 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(); | |
} | |
} | |
} | |
} | |
return { x: x, y: y }; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.getSelection().anchorNode.textContent.substring( | |
window.getSelection().extentOffset, | |
window.getSelection().anchorOffset) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment