Reputation: 1846
I am handling MouseDownEvent
and MouseUpEvent
on an Image
, in order to allow selection of part of the image. Most browsers will start dragging the image around unless preventDefault()
is called on the event, as is visible on this image:
The major downside of calling preventDefault()
is that if the focus was on, say, a TextBox
, it will remain there, even though the click on the Image
should have removed it.
I couldn't find a way to remove the focus from whatever widget currently happens to have it, or to give the focus to the Image
. My only workaround so far is to create a useless TextBox
that is not visible, and when I want to remove the focus I make it visible, give it the focus, and make it invisible again. Yuck. Any better suggestions?
Upvotes: 2
Views: 1689
Reputation: 9741
In order to make the image focusable you have to add the attribute tabindex
to the element, then you can call the Element.focus()
method to put the focus on the image when the user clicks on it.
final Image i = new Image("http:...");
i.getElement().setAttribute("tabindex", "0");
i.addMouseDownHandler(new MouseDownHandler() {
public void onMouseDown(MouseDownEvent event) {
event.preventDefault();
i.getElement().focus();
}
});
Another way if you dont need the image focusable, is just handling the dragStart
event and prevent the default here instead of in the mouse down and up handlers.
i.addDragStartHandler(new DragStartHandler() {
public void onDragStart(DragStartEvent event) {
event.preventDefault();
}
});
Upvotes: 3