JavaScript document.caretRangeFromPoint() Method

You are Here:

JavaScript document.caretRangeFromPoint() Method

The document.caretRangeFromPoint() method returns a Range object for the document fragment under the specified coordinates.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body onclick="myFunction(event)"> <p>click anywhere within this paragraph.</p> <script> function myFunction(e){ var range = document.caretRangeFromPoint(e.clientX, e.clientY); console.log(range); } </script> </body> </html>

Syntax

document.caretRangeFromPoint(x, y)

Parameter Values

ValueTypeExplanation
xRequiredA horizontal position within the current viewport.
yRequiredA vertical position within the current viewport.

Get Text under the Specified Coordinates

In the following example, we will get the text under the specified coordinates when the user clicks the paragraph.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body onclick="myFunction(event)"> <p>Click anywhere within this paragraph.</p> <p id="point"></p> <script> var x = document.getElementById("point"); var txt = document.getElementsByTagName("p")[0].innerText; var len = txt.length; function myFunction(e){ var range = document.caretRangeFromPoint(e.clientX, e.clientY); var start = txt.substring(range.startOffset, len); x.innerHTML = "<strong>Range:</strong> " + start; } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author