Cool tip of the day: Where in the DOM is your mouse?

What, elementFromPoint isn’t good enough for you? Well, in my case, no. For Verbosio, it would help a great deal to convert a mouse point to a DOM range point (think scripted selections, drag & drop like Pencil does, etc.). DOM ranges form, among other things, the basis for Mozilla’s selection algorithms.

Fortunately, there’s a way to figure it out. Just ask the mouse event for the range coordinates. Literally.

window.addEventListener("mousemove", {
handleEvent: function(aEvt) {
this.rangeParent = aEvt.rangeParent;
this.rangeOffset = aEvt.rangeOffset;
}, true);

This comes to us courtesy of the nsIDOMNSUIEvent interface.

The funny thing is, I knew about this back in 2002, when I was writing my book for Sams Publishing. I forgot about it sometime over the past six years (and I admit now that the book’s been only partially useful since then, missing certain bits of info I would’ve liked to know then).

Now, imagine using this to give a visual indicator where a given element you’re dragging will be dropped in a HTML or XML document…

One thought on “Cool tip of the day: Where in the DOM is your mouse?”

Comments are closed.