June 16, 2010

Google Closure menu with one selected item

Google Closure provides some UI widgets which you can use on your pages. One of such widgets is a menu widget.

In short, to produce a menu you'd need two pieces of code:

Here is an HTML piece:

<ul id="menu">
   <li class="goog-menuitem goog-option" id="item1">Item 1</li>
   <li class="goog-menuitem goog-option" id="item2">Item 2</li>
   <li class="goog-menuitem goog-option" id="item3">Item 3</li>
</ul>

And here is a JavaScript piece using Closure Library:
var menu = new goog.ui.Menu();
menu.decorate(goog.dom.getElement('menu'));


This will produce a menu which will maintain styles and dispatch events. The goog-option class makes menu items selectable. When a user clicks on an any element, the clicked element will get goog-option-selected style.
But when a user clicks on another item, that item's element will get this style too and you will end up with two selected elements. This is the default behavior and it is suitable for most of menu-like cases.

But what if you have a menu with single-select options, like a plain old HTML radio-group?
Then you need to handle selected items manually. I chose to implement a menu listener to manually deselect all previously selected elements:


goog.events.listen(menu, goog.ui.Component.EventType.ACTION, function(e) {
   /** @type {string} */
   var text = goog.dom.getTextContent(e.target.getElement());
   menu.forEachChild(function(c) {
       if (c != e.target) {
           c.setSelected(false);
           c.setChecked(false);
       }
   });
   caption.getElement().innerHTML = text;
} );

1 comment:

Unknown said...

Borgata Hotel Casino & Spa - JTR Hub
Located in 출장안마 Atlantic City, Borgata Hotel casinosites.one Casino & Spa offers the gri-go.com finest in amenities and entertainment. ventureberg.com/ It also 바카라 사이트 provides a seasonal outdoor swimming