Skip to content

Instantly share code, notes, and snippets.

@adamgotterer
Last active December 30, 2015 22:59
Show Gist options
  • Save adamgotterer/7897574 to your computer and use it in GitHub Desktop.
Save adamgotterer/7897574 to your computer and use it in GitHub Desktop.
Identify en email address under the cursor using rangy
// Still a work in progress
// NOTE: Requires Rangy 1.3alpha to use the word options with expand
// NOTE: Must include the core and the text select libraries
// TODO: Update loop to use rangy node iterator
// TODO: Only return email addresses
function getEmailUnderCursor(elem, x, y) {
if(elem.nodeType == elem.TEXT_NODE) {
//var doc_range = elem.ownerDocument.createRange();
var range = rangy.createRange();
range.selectNodeContents(elem);
//range.selectNodeContents(elem);
var currentPos = 0;
var endPos = range.endOffset;
while(currentPos+1 < endPos) {
range.setStart(elem, currentPos);
range.setEnd(elem, currentPos+1);
//console.log(range);
var client_rect = range.nativeRange.getBoundingClientRect();
if(client_rect.left <= x && client_rect.right >= x &&
client_rect.top <= y && client_rect.bottom >= y) {
range.expand('word', {
wordOptions: {
wordRegex: /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/gi
}
});
word = range.toString();
range.detach();
return word;
}
currentPos += 1;
}
} else {
for(var i = 0; i < elem.childNodes.length; i++) {
var range = rangy.createRange();
range.selectNodeContents(elem.childNodes[i]);
var client_rect = range.nativeRange.getBoundingClientRect();
if(client_rect.left <= x && client_rect.right >= x &&
client_rect.top <= y && client_rect.bottom >= y) {
range.detach();
return(getEmailUnderCursor(elem.childNodes[i], x, y));
} else {
range.detach();
}
}
}
return(null);
}
document.addEventListener("mousemove", function(e) {
getEmailUnderCursor(e.target, e.x, e.y);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment