Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT: Add an event handler on all div elements

Tags:

gwt

How to add an event handler on all div elements with GWT? I tried the following code but the window alerts are not fired up (But "etvoila" class is set up):

  private NodeList<Element> pageDIVElements;
  public void initDiv() {
    MyDIVEventHandler handler = new MyDIVEventHandler();
    pageDIVElements = Document.get().getElementsByTagName("div");
    for (int i = 0; i < pageDIVElements.getLength(); i++) {
      Element elem = pageDIVElements.getItem(i);
      elem.addClassName("etvoila");
      com.google.gwt.user.client.Element castedElem = (com.google.gwt.user.client.Element) elem;
      DOM.setEventListener(castedElem, handler);
    }

class MyDIVEventHandler implements EventListener {
  private Element divElement;
  @Override
  public void onBrowserEvent(Event event) {

    Window.alert("Yeepee");
    if (event.equals(Event.ONMOUSEOVER)) {
      Window.alert("ONMOUSEOVER");
      divElement = Element.as(((NativeEvent) event).getEventTarget());
      divElement.setPropertyString("background-color", "#C6D4E6");
    } else if (event.equals(Event.ONMOUSEOUT)) {
      divElement = Element.as(((NativeEvent) event).getEventTarget());
      divElement.setAttribute("background-color", "");
    }else if (event.equals(Event.ONCLICK)) {
      divElement = Element.as(((NativeEvent) event).getEventTarget());
      divElement.setAttribute("background-color", "");
      Window.alert("ONCLICK");
    }
  }
}

What is wrong in this method?

like image 679
djondal Avatar asked Oct 20 '10 04:10

djondal


2 Answers

Looks like you negelected to sink the events that you want the listener to be notified of. In this case for example I would add the following into initDiv to element or the relevant children.

DOM.sinkEvents(elem, Event.ONCLICK | Event.ONMOUSEOUT | Event.ONMOUSEOVER);
like image 53
Gerhard Davids Avatar answered Oct 29 '22 13:10

Gerhard Davids


Similarly to this question, you can wrap it in a Label.

NodeList<Element> elems = Document.get().getElementsByTagName("div");
for (int i = 0; i < elems.getLength(); i++) {
  Element elem = elems.get(i);
  Label l = Label.wrap(elem);
  l.addClickHandler(new ClickHandler() {
    @Override
    public void onClick(ClickEvent event) {
      Window.alert("yay!");
    }
  });
}
like image 30
Jason Hall Avatar answered Oct 29 '22 13:10

Jason Hall