Skip to content

Instantly share code, notes, and snippets.

@matt-west
Created June 22, 2011 18:13
Show Gist options
  • Save matt-west/1040721 to your computer and use it in GitHub Desktop.
Save matt-west/1040721 to your computer and use it in GitHub Desktop.
Get the position of selected text
/*
* Script Name:
* Get Selected Text Position
*
* Description:
* Get the position of a selectedRange object.
*
* License:
* MIT
*/
// Get the selected text
var range = window.getSelection().getRangeAt(0);
// Create a dummy element with the id 'pagerank' and insert this into the range
var dummy = document.createElement("span");
dummy.id = "pagemark";
range.insertNode(dummy);
// Get the dummy element
var box = document.getElementById("pagemark");
// Find it's position in the page
var y = box.offsetTop;
// Remove the dummy element
dummy.parentNode.removeChild(dummy);
return y;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment