get x/y of mouse click relative to a Dom mouse event.

92 views
Skip to first unread message

darkflame

unread,
Dec 2, 2012, 8:06:34 AM12/2/12
to Google Web Toolkit

I have some rather complex click handling code on a widget that has
the following sort of structure:

@Override
public void onBrowserEvent(Event event) {
event.cancelBubble(true);
event.preventDefault();

switch (DOM.eventGetType(event)) {

case Event.ONCLICK:


int x = Event.getCurrentEvent().getClientX();
int y = Event.getCurrentEvent().getClientY();

//how to get relative X/Y from the element that was clicked.

(stuff to run onclick)

case Event....(handles other forms of mouse action)




This works well, and lets handle everything as needed.
However, because I am using a Event rather then a ClickEvent, theres
no easy way to get the x/y of the click relative to the element that
fired it.
Is there any way to get this information?
I dont think I can cast to ClickEvent, so I need to parse over the
whole dom tree to convert from screen x/y to element-relative x/y?
Seems complex Is there a better way?

Thanks,
Thomas

Thomas Broyer

unread,
Dec 2, 2012, 8:40:49 AM12/2/12
to google-we...@googlegroups.com
Have a look at the code for getRelativeX/Y in MouseEvent.

BTW, why do you use Event.getCurrentEvent() instead of the 'event' argument?

You could also simply addClickHandler (or addDomHandler for ClickEvent.getType()) instead of overriding onBrowserEvent.

darkflame

unread,
Dec 2, 2012, 9:20:33 AM12/2/12
to google-we...@googlegroups.com
I did that mostly so I could separate it out into a method like I just did;

private void updateLastClickedLocation() {


int x = Event.getCurrentEvent().getClientX();
int y = Event.getCurrentEvent().getClientY();


InstructionProcessor.lastclicked_x = x - this.getElement().getAbsoluteLeft() + this.getElement().getScrollLeft() +
this.getElement().getOwnerDocument().getScrollLeft();

InstructionProcessor.lastclicked_y = y - this.getElement().getAbsoluteTop() + this.getElement().getScrollTop() +
this.getElement().getOwnerDocument().getScrollTop();

}

As I'll be using this a bit.

I'll try this now, the code was a lot more simple then I thought. I was thinking  getAbsoluteLeft on a element only returned X relative to its container.
This is all on a dragable absolute panel I made, with elements on it that are click-able with various mouse buttons while the container still being dragable itself. I could probably use a normal click handler, but I find it neater to use the switch method seeing as I am handling all the event types anyway.
Reply all
Reply to author
Forward
0 new messages