In GWT, Adding An Event Handler On Any Of The Host Page Tags
I want to add a MouseOver event handler for any tag. Let say just for the example, that I want to add the event handler for every anchor page in a legacy HTML page. Following the G
Solution 1:
You'll probably want to use Document.getElementsByTagName("a")
, which returns a NodeList
containing the elements, which can be cast to AnchorElement
s exposing the tag's href
attribute.
Try this code:
NodeList<Element> elems = Document.get().getElementsByTagName("a");
for (int i = 0; i < elems.getLength(); i++) {
Element elem = elems.getItem(i);
AnchorElement a = AnchorElement.as(elem);
if (!a.getHref().startsWith("http://yoursite.com")) {
a.setHref("http://yoursite.com/blockedpage");
}
}
To add an event handler, you can instead wrap the Element
in an Anchor
using wrap()
for (int i = 0; i < elems.getLength(); i++) {
Element elem = elems.get(i);
Anchor a = Anchor.wrap(elem);
a.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.alert("yay!");
}
});
}
(If the handler will always do the same thing, you'll want to only instantiate one ClickHandler
and add it to each element instead of creating a handler for each element)
Post a Comment for "In GWT, Adding An Event Handler On Any Of The Host Page Tags"