Selected text and xy coordinates

how to get selected text and xy word coordinates at the same time

0
source share
4 answers

Just played on Google:

var txt = ""; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { // FireFox txt = document.getSelection(); } else if (document.selection) { // IE 6/7 txt = document.selection.createRange().text; } txt = txt.toString() 

There is no easy way to get the X / Y coordinates of the selected text. Because it depends on its location and container size, text font, text layout, and many other variables.

+2
source

To extend the answer to @MatuDuke, you can get the position of the selected text like this:

 var txt = window.getSelection(), range = txt.getRangeAt(0), boundary = range.getBoundingClientRec(); // Available positions: // boundary.top // boundary.bottom // boundary.left // boundary.right 

This will give you pixel values ​​relative to the viewport. However, it does not work in text areas, the problem I'm trying to solve now.

+1
source

I use this jQuery http://plugins.jquery.com/node/7411 plugin for the project and it works flawlessly. You can use jQuery to get the mouse position http://docs.jquery.com/Tutorials:Mouse_Position

Here is a sample code that I worked on

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script type="text/javascript" src="jquery.textselect.js"></script> <script type="text/javascript"> $(function(){ $('#select').bind('textselect click', function(e){ console.log(e.text); console.log(e.pageX); }) }); </script> <!-- Date: 2010-11-05 --> </head> <body> <div id="select"> This is a simple select test </div> </body> </html> 
0
source

You can try something like this

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script type="text/javascript" src="jquery.textselect.js"></script> <script type="text/javascript"> $(function(){ $('#select').bind('textselect click', function(e){ console.log(e.text); console.log(e.pageX); var selected_text = e.text var original_text = $(this).text(); var parts = original_text.replace(e.text, "/").split("/"); for(i in parts) { console.log(parts[i]) } }) }); </script> <!-- Date: 2010-11-05 --> </head> <body> <div id="select"> This is a simple select test </div> </body> </html> 
0
source

All Articles