Does anyone know if it's possible to obtain the text that the mouse pointer is over in a web page?
Some assumptions can be made:
I'm aware of the Selection API, which allows you to return the selected text. But this is almost the opposite of that: A way to track the pointer, and obtain whatever content it passes over, ideally down to a single word basis, and then select it via code.
I can think of ways to achieve this by rendering the text to a canvas, then tracking pointer movement across the canvas, but I was hoping to find a more 'normal' approach.
Using document.elementFromPoint, you can find the element your mouse is hovering over. All you need is an event handler that updates a record of your mouse movement.
var pointer = {x: 0, y: 0};
window.addEventListener("mousemove",function(e) {
pointer.x = e.clientX;
pointer.y = e.clientY;
});
function getTextAtPointer() {
return document.elementFromPoint(pointer.x,pointer.y).textContent;
}
The only problem with this is that it won't tell you what word you're hovering over. The only solution I can think of would be to parse the text content and wrap every word in a span tag, then call document.elementFromPoint again to get which specific span. Doing this sounds like a heavy load, so hopefully there's an easier way to go about this problem.
EDIT
I've decided to try the method of replacing every word with span tags, and when I tested it, it didn't seem to affect performance in any perceivable way, so feel free to try it yourself. Here's the updated getTextAtPointer function.
function getTextAtPointer() {
var elem = document.elementFromPoint(pointer.x,pointer.y);
for(var i=elem.childNodes.length-1; i>=0; i--) {
var node = elem.childNodes[i];
if(node.nodeType==3) {
var words = node.textContent.split(/\s+/);
if(words.length>1) {
var frag = document.createDocumentFragment();
for(var j=0; j<words.length; j++) {
if(words[j].length>0) {
var span = document.createElement("span");
span.textContent = words[j];
frag.appendChild(span);
if(j!=words.length-1) {
frag.appendChild(document.createTextNode(" "));
}
}
}
elem.replaceChild(frag,node);
}
}
}
var word = document.elementFromPoint(pointer.x,pointer.y).textContent;
if(word.search(/\s+/)!=-1) {
return "";
}
return word;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With