Roger Chan
Roger Chan

Reputation: 1393

How to get DOM element by using mouse pointing position in dart script?

How to get DOM element by using mouse pointing position in dart script? Did dart have any library for this?

Upvotes: 4

Views: 168

Answers (2)

Daniel
Daniel

Reputation: 4301

From the mouse events (onMouseDown, onMouseMove, etc.) you get a MouseEvent. This MouseEvent has an attribute target that shows you the element under the mouse pointer. The code would look like that:

document.onMouseMove.listen((MouseEvent e) {
  Element target = e.target;
  print(target.id);
});

Upvotes: 2

Justin Fagnani
Justin Fagnani

Reputation: 11171

Document has a method elementFromPoint which is supposed to do what you want, but I find that's it's not that useful in practice. Often times you have some elements obscuring the ones that you want to locate by mouse, or you need all the elements under a point, not just the top-most one.

I tend to roll my own logic to find an element, but you do have to be careful because an element is not always where it claims to be. CSS transforms in particular can throw things off.

Here's the basic idea though:

Iterable<Element> getElementsAt(Element container, Point p) =>
    container.children.where((c) => containsPoint(c.offset, p));

bool containsPoint(Rectangle r, Point p) =>
    r.left <= p.x && r.right >= p.x && r.top <= p.y && r.bottom >= p.y;

Upvotes: 3

Related Questions