Arif AydınClients leave feedback on websites by pointing: "this button", "that heading". If you build a tool...
Clients leave feedback on websites by pointing: "this button", "that heading". If you build a tool that lets them click and drop a pin, the obvious approach is to store the click as page coordinates. It breaks almost immediately. The client is on a 1440px laptop, the developer opens it on a 1920px monitor, a banner loads late, the font swaps, and the pin is now floating over the wrong thing.
Here's the approach I ended up with while building Pinmarkup's feedback widget. It's not clever, but it holds up.
On click, find the element under the cursor (document.elementFromPoint, skipping the widget's own Shadow DOM host) and store a reference to it, plus where inside it the click landed:
const r = el.getBoundingClientRect();
anchor.point = {
x_percent: ((clientX - r.left) / r.width) * 100,
y_percent: ((clientY - r.top) / r.height) * 100,
};
Percentages of the element's own box mean the pin moves and scales with the element, whatever the viewport does.
The reference has to survive a reload, so it's a CSS selector. The order of preference:
data-testid if the element has one (developers rarely change these).id. Lots of ids are generated (:r3:, radix-…, headlessui-…, long hex runs), so they're filtered out with a regex. A generated id is worse than none: it resolves today and silently fails tomorrow.tag:nth-of-type() path, walked upward one segment at a time, stopping at the first suffix that is unique. If an ancestor has a stable id, the path is anchored there, which keeps it short.Every candidate is checked with document.querySelectorAll(sel).length === 1 && found[0] === el. A selector that matches two elements is a bug waiting to happen, so it's rejected.
For a dragged rectangle, probe a few points (start, centre, corners), walk up each ancestor chain, and keep the smallest element whose box fully contains the rectangle. Store the rectangle as percentages of that element. Anchoring an area to <body> would bring back exactly the problem we were avoiding.
Alongside the selector, store the element's document rect and the first 80 characters of its text. When the selector no longer resolves (the page was redesigned), you still know roughly where it was and what it said, which is enough for a human to understand the comment.
If you've solved anchoring differently (text-quote anchors like the Web Annotation spec, MutationObserver tracking), I'd love to hear how it held up.
I'm building Pinmarkup, a website feedback tool where clients pin comments on the live site without an account. It's in beta.