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 GWT guide, I was able to use their a JSNI method suggested to retrieve all anchor tags after correcting small errors (missing parenthesis and types).
However, I want to use the elements collected in the ArrayList and bind all of them to an event handler. How can I do that?
The code I wrote is listed below:
private native void putElementLinkIDsInList(BodyElement elt, ArrayList list) /*-{
var links = elt.getElementsByTagName("a");
for (var i = 0; i < links.length; i++ ) {
var link = links.item(i);
link.id = ("uid-a-" + i);
list.@java.util.ArrayList::add(Ljava/lang/Object;) (link.id);
}
}-*/;
/**
* Find all anchor tags and if any point outside the site, redirect them to a
* "blocked" page.
*/
private void rewriteLinksIterative() {
ArrayList links = new ArrayList();
putElementLinkIDsInList(Document.get().getBody(), links);
for (int i = 0; i < links.size(); i++) {
Element elt = DOM.getElementById((String) links.get(i));
rewriteLink(elt, "www.example.com");
}
}
/**
* Block all accesses out of the website that don't match 'sitename'
*
* @param element
* An anchor link element
* @param sitename
* name of the website to check. e.g. "www.example.com"
*/
private void rewriteLink(Element element, String sitename) {
String href = DOM.getElementProperty(element, "href");
if (null == href) {
return;
}
// We want to re-write absolute URLs that go outside of this site
if (href.startsWith("http://")
&& !href.startsWith("http://" + sitename + "/")) {
DOM.setElementProperty(element, "href", "http://" + sitename
+ "/Blocked.html");
}
}
You’ll probably want to use
Document.getElementsByTagName("a"), which returns aNodeListcontaining the elements, which can be cast toAnchorElements exposing the tag’shrefattribute.Try this code:
To add an event handler, you can instead wrap the
Elementin anAnchorusingwrap()(If the handler will always do the same thing, you’ll want to only instantiate one
ClickHandlerand add it to each element instead of creating a handler for each element)