Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get bounding rectangle of selected text javascript

Tags:

javascript

I use this code How can I position an element next to user text selection? to get the position of the selected text, but it doesn't work for the selected text inside an input. Sometimes the position is 0.

Is there some universal method for detecting the position of the selected text?

I want to show a tooltip on mouseup or dblclick the selected text.

like image 687
Andrew Fount Avatar asked Apr 17 '18 21:04

Andrew Fount


3 Answers

You can use the following code to get the position of selected text:

var selection = window.getSelection();
var getRange = selection.getRangeAt(0); 
getRect = getRange.getBoundingClientRect();
like image 81
Mahipal Avatar answered Nov 04 '22 22:11

Mahipal


You can use getSelection api. After selection a text run below code in console.

var selection = window.getSelection()
var baseOffset = selection.baseOffset
var length = selection.focusOffset -selection.baseOffset
var text = selection.focusNode.data.splice(baseOffset, length)
like image 30
DrEarnest Avatar answered Nov 04 '22 23:11

DrEarnest


If you just need to get the position where the user doubleclicked, use the following snippet.

$('#thatInput').on('dblclick', function (e) {
  alert('Position X: ' + e.clientX + '\nPosition Y: ' + e.clientY);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="thatInput">
like image 41
Script_Coded Avatar answered Nov 04 '22 23:11

Script_Coded