tags:

views:

179

answers:

2

I have an HTML document. In that document, there is an element (like button, div, a) with an ID. I know I can use:

Document.get().getElementById("id");

to find the required element in the HTML file. How can I add a Click handler to it? ClickHandlers only seem to be available on the Button class.

Thanks

+1  A: 

If you're trying to add a ClickHandler to a <button>, you can do that with Button.wrap().

For an <a> yo can use Anchor.wrap() (Anchors only have ClickListeners, not ClickHandlers...yet)

For a <div> you can use Label.wrap() (Labels are just <div>s).

Jason Hall
Perfect! You've been super helpful. I kept trying to do like new Button(Element element). Thanks!
Honza Pokorny
A: 

Suggestion : Try learning how to use UiBinder (added in GWT 2.0).

In your case, you could have done :

yourView.ui.xml

...
<g:Button ui:field="btnName" />
...

yourView.java

public class yourView extends Composite {
    interface MyUiBinder extends UiBinder<LayoutPanel, yourView> {}
    private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

    @UiField Button btnName;

    public yourView() {
        initWidget(uiBinder.createAndBindUi(this));
    }

    @UiHandler("btnName")
    void handleClick(ClickEvent e) {
        //Do whatever
    }
}

With "@UiHandler" you can add any handler the widget can support (implement Has****Handler). Adding other element to that structure is easy and FAST and you can add any kind of handler to it. @UiField create a variable containing the instance of the element that is manipulatable anywhere in your class.

Zwik
This works if the UI is built in GWT, but his question was asking about adding click handlers (and other GWT functionality) to existing HTML on the page. If he was building the whole page in GWT, however, this would definitely be the way to go.
Jason Hall