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?
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);
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!");
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With