9

I'm trying to create a link (anchor) in GWT that can be clicked and it's ClickEvent can be processed, while at the same time this anchor wouldn't reload the page. This basically means that a href must not be set.

In javascript this is done like this:

<a href="javascript:handleAnchorClick();">Link</a> 

or with

<a href="#" onclick="return handleAnchorClick()">Link</a>  

where handleAnchorClick() returns false.

What would be the best way to achieve this in GWT?

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • If you set an href that starts with a `#` the page won't be reloaded, but the history stack will be changed, and you can respond to that event. – Riley Lark Dec 05 '10 at 04:36
  • Exactly, the history stack is changed and I don't want to deal with that just to have a clickable link. – Peter Knego Dec 05 '10 at 08:11

4 Answers4

12

Use tha Anchor element, and call its addClickListener() method and add in what ever logic you wish. This sort of anchor doesn't reload the page.

Chii
  • 14,540
  • 3
  • 37
  • 44
10

Listeners are deprecated in GWT use handlers

Something like that :

Anchor a = new Anchor("hi");
a.addClickhandler(new ClickHandler() {
     @Override
     public void onClick(ClickEvent event) {
           Window.alert("hi");
     }

});
  • AddClickhandler doesn't works, it must be "addClickHandler", Also forgot the closing brace, this code compiles: btnLogout.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.alert("hi"); } }); – XhkUnlimit Jul 03 '14 at 20:29
8

As you describe, using href="#" will reload the page.

This is what you can do in UIBinder:

    <g:Anchor ui:field="myScriptedAnchor" href="javascript:;">
        MyScriptedAnchorText
    </g:Anchor>

Then you can do whatever you want handling the ClickEvent in the view implementation.

    @UiHandler("myScriptedAnchor")
    void onMyScriptedAnchorClick(ClickEvent event) {
        // TODO whatever you want to do...
    }
RalfWestbrock
  • 113
  • 2
  • 5
8

Don't forget to add a style to anchor otherwise it doesnt behave like a normal html link:

.anchor {
            text-decoration: underline;
            font-weight: bold;
            cursor: pointer;
            display: block;
        }
Gambo
  • 1,572
  • 3
  • 26
  • 52