gdurelle / gwt-tagcloud

A gwt composite to create a tag cloud
1 stars 1 forks source link

ClickEvent support for tags #4

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I like your tag cloud, but I would like to define an action to be performed 
when a tag (in my case a word tag) is click, instead of just link.

Adding this, I think, is relatively simple - a WordTag (maybe ImageTag too) 
could have an additional parameter - ClickHandler - in the constructor (or, 
ideally a method addClickHandler(...)) and a getter for this handler (or 
handlers). Then, while rendering the tag cloud, insert a call 
inlineHTML.addClickHandler(wordtag.getClickHandler()) [InlineHTML implements 
the GWT HasClickHandlers interface], and remove the 'href' property from the 
<a> tag in the html content (the <a> tag is no longer needed then, but it 
spares work needed to style this bit). 

Original issue reported on code.google.com by joanna.k...@gmail.com on 4 Feb 2011 at 9:30

GoogleCodeExporter commented 9 years ago
I agree, the fact that it only accepts a String and return a String is a bit 
restrictive and against good OO practices. I need to add a tool-tip and I have 
no object to deal with. 

Original comment by br...@109forest.com on 5 Dec 2014 at 8:13

GoogleCodeExporter commented 9 years ago
I was able to find a fairly simple workaround for this. Luckily, it doesn't 
require having to extend the existing API either. You can add a DomHandler to 
the tag cloud itself that will be triggered for every click event. 
Unfortunately, this will be triggered if the user clicks anywhere within the 
tag cloud, not just on one of the generated anchor tags. But from using the GWT 
ClickEvent, you can figure out which part of the tag cloud was clicked. And if 
it was on a tag, retrieve its text if needed.

Here's an example snippet of how I was able to achieve this:

TagCloud cloud = new TagCloud();

// Add words to tag cloud

cloud.addDomHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
        event.preventDefault();   // Ignore URL link
        Element clickedElement = Element.as(event.getNativeEvent().getEventTarget());

        // Check if user clicked on anchor tag
        if (clickedElement.getNodeName().equalsIgnoreCase("a")) {

           String selectedTag = clickedElement.getInnerText();

           // Do whatever you need with the selected tag

        }
    }
}, ClickEvent.getType());

Original comment by jkaltenb...@gmail.com on 30 Jan 2015 at 6:21