Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i find out which GWT element has focus?

I would like to find out, in GWT, which element currently has focus. Basically i was working on virtual keyboard in our application. All keys are working fine except tab key. If i get focused element then i can work out the tab key code.

In javascript and jquery we can get this using document.activeElement. Hope some body will put me in right way to achieve this.

Help would be appreciated.

like image 999
Kiran Avatar asked Jan 20 '12 09:01

Kiran


3 Answers

The fact that it's not supported in "all browsers" is only important if your app is targeting all browsers. activeElement is currently supported by quite a few browsers Why is there no isFocused() in GWT?.

I needed something similar, I needed to know from inside a widget if it had focus. I did the following

protected native boolean hasFocus(Element element) /*-{
   return element.ownerDocument.activeElement == element;
}-*/; 

I needed to pass in the current element to get the proper document, just calling

document.activeElement;

did not give me the document I needed. You could likely do the same but pass in the a different element (RootPanel element maybe?) and return the in focus Element rather than a bool.

protected native Element elementInFocus(Element element) /*-{
   return element.ownerDocument.activeElement;
}-*/; 
like image 112
RobRolls Avatar answered Oct 24 '22 23:10

RobRolls


document.activeElement doesn't work in all browsers so there's no support for that in GWT. You could maybe use focus&blur handlers to keep track which element has it.

like image 33
milan Avatar answered Oct 24 '22 21:10

milan


Short template:

public class IntBox extends com.google.gwt.user.client.ui.IntegerBox {

private boolean focused=false;

public IntBox(){

        addFocusHandler(new FocusHandler() {

            @Override
            public void onFocus(FocusEvent event) {
                focused=true;
            }
        });

        addBlurHandler(new BlurHandler() {

            @Override
            public void onBlur(BlurEvent event) {
                focused=false;
            }
        });

    }

    public boolean isFocused() {
        return focused;
    }

}
like image 42
user1817599 Avatar answered Oct 24 '22 21:10

user1817599