Share the post "How To Get Rectangle Bounds Of Selected Text In Javascript"
User Tim Down from the Stack Overflow forum provided a very handy function to get the rectangle bounds of selected text in Javascript.
This is mighty useful in cases like mine where I wanted to control the visibility of the context menu and that I required it to appear only when the mouse cursor is within the selected text bound.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function getSelectionBound() { var sel = document.selection, range; var x = 0, y = 0, width = 0, height = 0; if (sel) { if (sel.type != "Control") { range = sel.createRange(); x = range.boundingLeft; y = range.boundingTop; width = range.boundingWidth; height = range.boundingHeight; } } else if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(0).cloneRange(); if (range.getBoundingClientRect) { var rect = range.getBoundingClientRect(); x = rect.left; y = rect.top; width = rect.right - rect.left; height = rect.bottom - rect.top; } } } return { x: x, y: y, width: width , height: height }; } |