javascript selection/range coordinates

I would like to absolute-position a div on either the initial or terminal corner of a text selection, as the user drags their mouse along. Unfortunately, Range only provides the index position, not the x/y coordinates. I think there might be a way to do this with range.insertNode, but only for one side. (This might also help someone position an auto-complete box under a contenteditable.)

How can I get the x/y coordinates of a text selection, or of the text cursor?



Works in chrome/webkit, positioning the div after the last-selected letter. Usually.

<script type="text/javascript" src=""></script>
var $div;
var last;
function find() {
    var selection = window.getSelection();
    var text = selection.toString();
    if (last==text) return; else last=text; // prevent needless computations if no changes to selection
    if (selection.rangeCount==0) return;

    var range = selection.getRangeAt(0);
    var $span= $("<span/>");

    newRange = document.createRange();
    newRange.setStart(selection.focusNode, range.endOffset);
    newRange.insertNode($span[0]); // using 'range' here instead of newRange unselects or causes flicker on chrome/webkit

    var x = $span.offset().left;
    var y = $span.offset().top;
    $div.text(x+" "+y);
$(window).load(function() {
    $("body").keydown(function(e) {
    $("body").mousemove(function(e) {
    $div=$("<div style='border:1px solid red;background:white; position:absolute;'>").appendTo($("body"));
<body><p>the quick brown fox</p><ul><li>jumps <i>over</i></li></ul><p>the lazy dog</p></body>

You would have to get the mouse position from the mouse move event. Then you can get the position of the text input element and do the math (make the mouse position relative).


Here is a page where you can get JavaScript code that will get the caret position in pixels.

If you want to use JQuery, you can use this


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.