Posts Tagged ‘drop down’

Simple drop-downs using YAHOO.util.Dom.isAncestor

Saturday, May 2nd, 2009

The Yahoo! User Interface Library (YUI) has a bunch of very nifty little methods to make complex tasks easier. One that immediately stood out to me was isAncestor, as I can attest first-hand to the cross-browser troubles when trying to detect ancestry in the DOM. Although a very basic concept, most drop-down code often becomes bloated or restrictive. I’m not advocating the use of JavaScript drop-downs over a CSS method, but there are some added benefits of using JS to achieve this effect:

  1. Clean markup, no need for conditional comments
  2. The ability to animate show and hide events
  3. Added styling opportunities, won’t break so long as the nested list structure remains in tact

Below is a simple example of how to use YUI’s isAncestor to create flyout menus with HTML and CSS.

(function() {
	function mouseover(e) {
		var menu = this.getElementsByTagName('ul')[0];
		YAHOO.util.Dom.setStyle(menu, 'display', 'block');
	};

	function mouseout(e) {
		if (!YAHOO.util.Dom.isAncestor(this, e.relatedTarget) || e.relatedTarget == document.getElementsByTagName('html')[0]) {
			var menu = this.getElementsByTagName('ul')[0];
			YAHOO.util.Dom.setStyle(menu, 'display', 'none');
		}
	};
	YAHOO.util.Event.on(YAHOO.util.Dom.get('nav').getElementsByTagName('li'), 'mouseover', mouseover);
	YAHOO.util.Event.on(YAHOO.util.Dom.get('nav').getElementsByTagName('li'), 'mouseout', mouseout);
})();

See Example »

If you need something more complex, see the YUI MenuCreator page.

Posted in Programming | No Comments »