YUI 3.x Home -

YUI Library Examples: Focus Manager Node Plugin: Accessible TabView

Focus Manager Node Plugin: Accessible TabView

This example illustrates how to create an accessible tabview widget using the Focus Manager Node Plugin, Event's delegation support, and Node's support for the WAI-ARIA Roles and States.

Today's News

Setting Up the HTML

The tabs in the tabview widget will be represented by a list of <a> elements whose href attribute is set to the id of an <div> element that contains its content. Therefore, without JavaScript and CSS, the tabs function as in-page links.

  1. <h3 id="tabview-heading">Today's News</h3>
  2. <div id="tabview-1" class="yui3-tabview-loading">
  3. <ul>
  4. <li class="yui3-tab yui-tab-selected"><a href="#top-stories"><em>Top Stories</em></a></li>
  5. <li class="yui3-tab"><a href="#world-news"><em>World</em></a></li>
  6. <li class="yui3-tab"><a href="#entertainment-news"><em>Entertainment</em></a></li>
  7. <li class="yui3-tab"><a href="#sports-news"><em>Sports</em></a></li>
  8. <li class="yui3-tab"><a href="#technology-news"><em>Technology</em></a></li>
  9. </ul>
  10. <div>
  11. <div class="yui3-tabpanel yui-tabpanel-selected" id="top-stories">
  12. <!-- Tab Panel Content Here -->
  13. </div>
  14. <div class="yui3-tabpanel" id="world-news">
  15. <!-- Tab Panel Content Here -->
  16. </div>
  17. <div class="yui3-tabpanel" id="entertainment-news">
  18. <!-- Tab Panel Content Here -->
  19. </div>
  20. <div class="yui3-tabpanel" id="sports-news">
  21. <!-- Tab Panel Content Here -->
  22. </div>
  23. <div class="yui3-tabpanel" id="technology-news">
  24. <!-- Tab Panel Content Here -->
  25. </div>
  26. </div>
  27. </div>
<h3 id="tabview-heading">Today's News</h3>
<div id="tabview-1" class="yui3-tabview-loading">
    <ul>
        <li class="yui3-tab yui-tab-selected"><a href="#top-stories"><em>Top Stories</em></a></li>
        <li class="yui3-tab"><a href="#world-news"><em>World</em></a></li>
        <li class="yui3-tab"><a href="#entertainment-news"><em>Entertainment</em></a></li>
        <li class="yui3-tab"><a href="#sports-news"><em>Sports</em></a></li>
        <li class="yui3-tab"><a href="#technology-news"><em>Technology</em></a></li>
    </ul>
    <div>
        <div class="yui3-tabpanel yui-tabpanel-selected" id="top-stories">
            <!-- Tab Panel Content Here  -->
        </div>
        <div class="yui3-tabpanel" id="world-news">
            <!-- Tab Panel Content Here  -->
        </div>
        <div class="yui3-tabpanel" id="entertainment-news">
            <!-- Tab Panel Content Here  -->
        </div>
        <div class="yui3-tabpanel" id="sports-news">
            <!-- Tab Panel Content Here  -->
        </div>
        <div class="yui3-tabpanel" id="technology-news">
            <!-- Tab Panel Content Here  -->
        </div>
    </div>
</div>

For this example the content of each tab panel is created on the server using the YQL API to fetch the title and URL for news stories made available from the various Yahoo! News RSS feeds. Here's the PHP:

  1. function getFeed($sFeed) {
  2.  
  3. $params = array(
  4. "q" => ('select title,link from rss where url="http://rss.news.yahoo.com/rss/$sFeed"'),
  5. "format" => "json"
  6. );
  7.  
  8. $encoded_params = array();
  9.  
  10. foreach ($params as $k => $v) {
  11. $encoded_params[] = urlencode($k)."=".urlencode($v);
  12. }
  13.  
  14. $url = "http://query.yahooapis.com/v1/public/yql?".implode("&", $encoded_params);
  15.  
  16. $ch = curl_init();
  17. curl_setopt($ch, CURLOPT_URL, $url);
  18. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  19. $rsp = curl_exec($ch);
  20. curl_close($ch);
  21.  
  22. if ($rsp !== false) {
  23.  
  24. $rsp_obj = json_decode($rsp, true);
  25.  
  26. $results = $rsp_obj["query"]["results"]["item"];
  27.  
  28. $list = ""; // HTML output
  29.  
  30. $nResults = count($results);
  31.  
  32. if ($nResults > 10) {
  33. $nResults = 9;
  34. }
  35.  
  36. for ($i = 0; $i<= $nResults; $i++) {
  37.  
  38. $result = $results[$i];
  39.  
  40. $list.= <<< END_OF_HTML
  41.   <li>
  42.   <a href="${result["link"]}"><q>${result["title"]}</q></a>
  43.   </li>
  44. END_OF_HTML;
  45.  
  46. }
  47.  
  48. return ("<ul>" . $list . "</ul>");
  49.  
  50. }
  51.  
  52. }
  53.  
function getFeed($sFeed) {
 
    $params = array(
        "q" => ('select title,link from rss where url="http://rss.news.yahoo.com/rss/$sFeed"'),
        "format" => "json"
    );
 
    $encoded_params = array();
 
    foreach ($params as $k => $v) {
        $encoded_params[] = urlencode($k)."=".urlencode($v);
    }
 
    $url = "http://query.yahooapis.com/v1/public/yql?".implode("&", $encoded_params);
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $rsp = curl_exec($ch);
    curl_close($ch);
 
    if ($rsp !== false) {
 
        $rsp_obj = json_decode($rsp, true);
 
        $results = $rsp_obj["query"]["results"]["item"];
 
        $list = ""; // HTML output
 
        $nResults = count($results);
 
        if ($nResults > 10) {
            $nResults = 9;
        }
 
        for ($i = 0; $i<= $nResults; $i++) {
 
            $result = $results[$i];
 
            $list.= <<< END_OF_HTML
            <li>
                <a href="${result["link"]}"><q>${result["title"]}</q></a>
            </li>
END_OF_HTML;
 
        }
 
        return ("<ul>" . $list . "</ul>");
 
    }
 
}
 

Progressive Enhancement

To account for the scenario where the user has CSS enabled in their browser but JavaScript is disabled, the CSS used to style the tabview will be loaded via JavaScript using the YUI instance's built-in Loader.

  1. YUI({
  2.  
  3. base: "../../build/",
  4. modules: {
  5. "tabviewcss": {
  6. type: "css",
  7. fullpath: "assets/tabview.css"
  8. },
  9. "tabviewjs": {
  10. type: "js",
  11. fullpath: "assets/tabview.js",
  12. requires: ["node-focusmanager", "tabviewcss"]
  13. }
  14.  
  15. },
  16. timeout: 10000
  17.  
  18. }).use("tabviewjs");
YUI({
 
    base: "../../build/",
    modules: {
        "tabviewcss": {
            type: "css",
            fullpath: "assets/tabview.css"
        },
        "tabviewjs": {
            type: "js",
            fullpath: "assets/tabview.js",
            requires: ["node-focusmanager", "tabviewcss"]
        }
 
    },
    timeout: 10000
 
}).use("tabviewjs");

To prevent the user from seeing a flash unstyled content when JavaScript is enabled, a style rule is created using YUI's yui3-js-enabled class name that will temporarily hide the markup while the JavaScript and CSS are in the process of loading. For more on using the yui3-js-enabled class name, see the HIDING PROGRESSIVELY ENHANCED MARKUP section of the YUI Widget landing page.

  1. /* Hide the list while it is being transformed into a tabview. */
  2.  
  3. .yui3-js-enabled .yui3-tabview-loading {
  4. display: none;
  5. }
/*	Hide the list while it is being transformed into a tabview.	*/
 
.yui3-js-enabled .yui3-tabview-loading {
    display: none;
}

ARIA Support

Through the use of CSS and JavaScript the HTML for the tabview can be transformed into something that looks and behaves like a desktop tab control, but users of screen readers won't perceive it as an atomic widget, but rather simply as a set of HTML elements. However, through the application of the WAI-ARIA Roles and States, it is possible to improve the semantics of the markup such that users of screen readers perceive it as a tab control.

Keyboard Functionality

The keyboard functionality for the tabview widget will be provided by the Focus Manager Node Plugin. The Focus Manager's descendants attribute is set to a value of ".yui3-tab>a", so that only one tab in the tabview is in the browser's default tab flow. This allows users navigating via the keyboard to use the tab key to quickly move into and out of the tabview. Once the tabview has focus, the user can move focus among each tab using the left and right arrows keys, as defined by the value of the keys attribute. Lastly, the focusClass attribute is used to apply a class of yui-tab-focus to the parent <li> of each <a> when it is focused, making it easy to style the tab's focused state in each of the A-Grade browsers.

  1. YUI().use("*", function (Y) {
  2.  
  3. var tabView = Y.one("#tabview-1"),
  4. tabList = tabView.one("ul"),
  5. tabHeading = Y.one("#tabview-heading"),
  6. sInstructionalText = tabHeading.get("innerHTML");
  7. selectedTabAnchor = tabView.one(".yui3-tab-selected>a"),
  8. bGeckoIEWin = ((Y.UA.gecko || Y.UA.ie) && navigator.userAgent.indexOf("Windows") > -1),
  9. panelMap = {};
  10.  
  11.  
  12. tabView.addClass("yui3-tabview");
  13.  
  14. // Remove the "yui3-loading" class now that the necessary YUI dependencies are loaded and the
  15. // tabview has been skinned.
  16.  
  17. tabView.removeClass("yui3-tabview-loading");
  18.  
  19. // Apply the ARIA roles, states and properties.
  20.  
  21. // Add some instructional text to the heading that will be read by
  22. // the screen reader when the first tab in the tabview is focused.
  23.  
  24. tabHeading.set("innerHTML", (sInstructionalText + " <em>Press the enter key to load the content of each tab.</em>"));
  25.  
  26. tabList.setAttrs({
  27. "aria-labelledby": "tabview-heading",
  28. role: "tablist"
  29. });
  30.  
  31. tabView.one("div").set("role", "presentation");
  32.  
  33.  
  34. tabView.plug(Y.Plugin.NodeFocusManager, {
  35. descendants: ".yui3-tab>a",
  36. keys: { next: "down:39", // Right arrow
  37. previous: "down:37" }, // Left arrow
  38. focusClass: {
  39. className: "yui3-tab-focus",
  40. fn: function (node) {
  41. return node.get("parentNode");
  42. }
  43. },
  44. circular: true
  45. });
  46.  
  47.  
  48. // If the list of tabs loses focus, set the activeDescendant
  49. // attribute to the currently selected tab.
  50.  
  51. tabView.focusManager.after("focusedChange", function (event) {
  52.  
  53. if (!event.newVal) { // The list of tabs has lost focus
  54. this.set("activeDescendant", selectedTabAnchor);
  55. }
  56.  
  57. });
  58.  
  59.  
  60. tabView.all(".yui3-tab>a").each(function (anchor) {
  61.  
  62. var sHref = anchor.getAttribute("href", 2),
  63. sPanelID = sHref.substring(1, sHref.length),
  64. panel;
  65.  
  66. // Apply the ARIA roles, states and properties to each tab
  67.  
  68. anchor.set("role", "tab");
  69. anchor.get("parentNode").set("role", "presentation");
  70.  
  71.  
  72. // Remove the "href" attribute from the anchor element to
  73. // prevent JAWS and NVDA from reading the value of the "href"
  74. // attribute when the anchor is focused
  75.  
  76. if (bGeckoIEWin) {
  77. anchor.removeAttribute("href");
  78. }
  79.  
  80. // Cache a reference to id of the tab's corresponding panel
  81. // element so that it can be made visible when the tab
  82. // is clicked.
  83. panelMap[anchor.get("id")] = sPanelID;
  84.  
  85.  
  86. // Apply the ARIA roles, states and properties to each panel
  87.  
  88. panel = Y.one(("#" + sPanelID));
  89.  
  90. panel.setAttrs({
  91. role: "tabpanel",
  92. "aria-labelledby": anchor.get("id")
  93. });
  94.  
  95. });
  96.  
  97.  
  98. // Use the "delegate" custom event to listen for the "click" event
  99. // of each tab's <A> element.
  100.  
  101. tabView.delegate("click", function (event) {
  102.  
  103. var selectedPanel,
  104. sID = this.get("id");
  105.  
  106. // Deselect the currently selected tab and hide its
  107. // corresponding panel.
  108.  
  109. if (selectedTabAnchor) {
  110. selectedTabAnchor.get("parentNode").removeClass("yui3-tab-selected");
  111. Y.one(("#" + panelMap[selectedTabAnchor.get("id")])).removeClass("yui3-tabpanel-selected");
  112. }
  113.  
  114. selectedTabAnchor = this;
  115. selectedTabAnchor.get("parentNode").addClass("yui3-tab-selected");
  116.  
  117. selectedPanel = Y.one(("#" + panelMap[sID]));
  118. selectedPanel.addClass("yui3-tabpanel-selected");
  119.  
  120. creatingPaging(selectedPanel);
  121.  
  122. // Prevent the browser from following the URL specified by the
  123. // anchor's "href" attribute when clicked.
  124.  
  125. event.preventDefault();
  126.  
  127. }, ".yui3-tab>a");
  128.  
  129.  
  130. // Since the anchor's "href" attribute has been removed, the
  131. // element will not fire the click event in Firefox when the
  132. // user presses the enter key. To fix this, dispatch the
  133. // "click" event to the anchor when the user presses the
  134. // enter key.
  135.  
  136. if (bGeckoIEWin) {
  137.  
  138. tabView.delegate("keydown", function (event) {
  139.  
  140. if (event.charCode === 13) {
  141. this.simulate("click");
  142. }
  143.  
  144. }, ">ul>li>a");
  145.  
  146. }
  147.  
  148. });
YUI().use("*", function (Y) {
 
	var tabView = Y.one("#tabview-1"),
		tabList = tabView.one("ul"),
		tabHeading = Y.one("#tabview-heading"),
		sInstructionalText = tabHeading.get("innerHTML");
		selectedTabAnchor = tabView.one(".yui3-tab-selected>a"),
		bGeckoIEWin = ((Y.UA.gecko || Y.UA.ie) && navigator.userAgent.indexOf("Windows") > -1),
		panelMap = {};
 
 
	tabView.addClass("yui3-tabview");
 
	//	Remove the "yui3-loading" class now that the necessary YUI dependencies are loaded and the 
	//	tabview has been skinned.
 
	tabView.removeClass("yui3-tabview-loading");
 
	//	Apply the ARIA roles, states and properties.
 
	//	Add some instructional text to the heading that will be read by
	//	the screen reader when the first tab in the tabview is focused.
 
	tabHeading.set("innerHTML", (sInstructionalText + " <em>Press the enter key to load the content of each tab.</em>"));
 
	tabList.setAttrs({
		"aria-labelledby": "tabview-heading",
		role: "tablist"
	});
 
	tabView.one("div").set("role", "presentation");
 
 
	tabView.plug(Y.Plugin.NodeFocusManager, { 
			descendants: ".yui3-tab>a",
			keys: { next: "down:39", //	Right arrow
					previous: "down:37" },	// Left arrow
			focusClass: {
				className: "yui3-tab-focus",
				fn: function (node) {
					return node.get("parentNode");
				}
			},
			circular: true
		});
 
 
	//	If the list of tabs loses focus, set the activeDescendant 
	//	attribute to the currently selected tab.
 
	tabView.focusManager.after("focusedChange", function (event) {
 
		if (!event.newVal) {	//	The list of tabs has lost focus
			this.set("activeDescendant", selectedTabAnchor);
		}
 
	});
 
 
	tabView.all(".yui3-tab>a").each(function (anchor) {
 
		var sHref = anchor.getAttribute("href", 2),
			sPanelID = sHref.substring(1, sHref.length),
			panel;
 
		//	Apply the ARIA roles, states and properties to each tab
 
		anchor.set("role", "tab");
		anchor.get("parentNode").set("role", "presentation");
 
 
		//	Remove the "href" attribute from the anchor element to  
		//	prevent JAWS and NVDA from reading the value of the "href"
		//	attribute when the anchor is focused
 
		if (bGeckoIEWin) {
			anchor.removeAttribute("href");
		}
 
		//	Cache a reference to id of the tab's corresponding panel
		//	element so that it can be made visible when the tab
		//	is clicked.
		panelMap[anchor.get("id")] = sPanelID;
 
 
		//	Apply the ARIA roles, states and properties to each panel
 
		panel = Y.one(("#" + sPanelID));
 
		panel.setAttrs({
			role: "tabpanel",
			"aria-labelledby": anchor.get("id")
		});
 
	});
 
 
	//	Use the "delegate" custom event to listen for the "click" event
	//	of each tab's <A> element.
 
	tabView.delegate("click", function (event) {
 
		var selectedPanel,
			sID = this.get("id");
 
		//	Deselect the currently selected tab and hide its 
		//	corresponding panel.
 
		if (selectedTabAnchor) {
			selectedTabAnchor.get("parentNode").removeClass("yui3-tab-selected");
			Y.one(("#" + panelMap[selectedTabAnchor.get("id")])).removeClass("yui3-tabpanel-selected");
		}
 
		selectedTabAnchor = this;
		selectedTabAnchor.get("parentNode").addClass("yui3-tab-selected");
 
		selectedPanel = Y.one(("#" + panelMap[sID]));
		selectedPanel.addClass("yui3-tabpanel-selected");
 
		creatingPaging(selectedPanel);
 
		//	Prevent the browser from following the URL specified by the 
		//	anchor's "href" attribute when clicked.
 
		event.preventDefault();
 
	}, ".yui3-tab>a");
 
 
	//	Since the anchor's "href" attribute has been removed, the 
	//	element will not fire the click event in Firefox when the 
	//	user presses the enter key.  To fix this, dispatch the 
	//	"click" event to the anchor when the user presses the 
	//	enter key.
 
	if (bGeckoIEWin) {
 
		tabView.delegate("keydown", function (event) {
 
			if (event.charCode === 13) {
				this.simulate("click");
			}
 
		}, ">ul>li>a");
 
	}
 
});

Accessibility Sugar

One of the challenges faced by users of screen readers is knowing when you've left the context of a given control. In the case of this tabview, if it were adjacent to another ARIA-enabled widget, the user would know they've left the tabview when the screen reader announces the role of the adjacent widget. However, if the tabview is sitting alongside standard HTML content, it would be really difficult for the user to know when they've left the context of the active panel.

One solution to this problem is to add some additional navigation as the last child of each tab panel that allows the user to move to the previous and next panel in the tabview. This will not only help alert users of screen readers that they've reached the end of the tab's panel, but allow all keyboard users to move more quickly to the next/previous panel. Without this additionally navigation, keyboard users would typically have to press shift+tab to navigate back up to the list of tabs to move to the next/previous tab.

  1. var creatingPaging = function (panel) {
  2.  
  3. var listitem,
  4. sHTML = "";
  5.  
  6. if (!panel.one(".paging")) {
  7.  
  8. listitem = selectedTabAnchor.get("parentNode");
  9.  
  10. if (listitem.previous()) {
  11. sHTML += '<button type="button" class="yui3-tabview-prevbtn">Previous Tab Panel</button>';
  12. }
  13.  
  14. if (listitem.next()) {
  15. sHTML += '<button type="button" class="yui3-tabview-nextbtn">Next Tab Panel</button>';
  16. }
  17.  
  18. panel.append('<div class="paging">' + sHTML + '</div>');
  19.  
  20. }
  21.  
  22. };
  23.  
  24. creatingPaging(Y.one(".yui3-tabpanel-selected"));
  25.  
  26.  
  27. tabView.delegate("click", function (event) {
  28.  
  29. var node = selectedTabAnchor.get("parentNode").previous().one("a");
  30.  
  31. tabView.focusManager.focus(node);
  32. node.simulate("click");
  33.  
  34. }, ".yui3-tabview-prevbtn");
  35.  
  36.  
  37. tabView.delegate("click", function (event) {
  38.  
  39. var node = selectedTabAnchor.get("parentNode").next().one("a");
  40.  
  41. tabView.focusManager.focus(node);
  42. node.simulate("click");
  43.  
  44. }, ".yui3-tabview-nextbtn");
var creatingPaging = function (panel) {
 
    var listitem,
        sHTML = "";
 
    if (!panel.one(".paging")) {
 
        listitem = selectedTabAnchor.get("parentNode");
 
        if (listitem.previous()) {
            sHTML += '<button type="button" class="yui3-tabview-prevbtn">Previous Tab Panel</button>';
        }
 
        if (listitem.next()) {
            sHTML += '<button type="button" class="yui3-tabview-nextbtn">Next Tab Panel</button>';
        }
 
        panel.append('<div class="paging">' + sHTML + '</div>');
 
    }
 
};
 
creatingPaging(Y.one(".yui3-tabpanel-selected"));
 
 
tabView.delegate("click", function (event) {
 
    var node = selectedTabAnchor.get("parentNode").previous().one("a");
 
    tabView.focusManager.focus(node);
    node.simulate("click");
 
}, ".yui3-tabview-prevbtn");
 
 
tabView.delegate("click", function (event) {
 
    var node = selectedTabAnchor.get("parentNode").next().one("a");
 
    tabView.focusManager.focus(node);
    node.simulate("click");
 
}, ".yui3-tabview-nextbtn");

Copyright © 2011 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings