Add Tabbed Navigation - Exercise

Contact Us or call 1-877-932-8228
Add Tabbed Navigation - Exercise

Add Tabbed Navigation

Duration: 20 to 40 minutes.

Continue to use index.html. Use the file jqy-events/Exercises/js/tabs.js. Your task is to create tabbed navigation for the two div.module elements (blog and specials). To accomplish this:

  1. Hide all of the modules (the div.module elements), but first add the tabContent class to them.
  2. Create an unordered list element before the first module. Add the tabBar class to the unordered list you created.
  3. Iterate over the modules using $.fn.each. For each module, use the text of the h2 element as the text for a list item that you add to the unordered list element.
  4. When you create each list item, bind a click event to it that:
    1. Shows the related module, and hides any other modules
    2. Adds a class of current to the clicked list item
    3. Removes the class current from the other list item(s)
    4. For the click handler to "remember" the associated module, you can either use data, or a local variable created in the outer function (the function supplied to each)
  5. Add the tabs class to each list item
  6. Finally, show the first tab. You should also ensure that the styling of the tabs matches what is showing, that is, the first tab should have the current class, and the others not.

Solution:

jqy-events/Solutions/js/tabs.js
$(document).ready(function() {
	// Find all the modules, add the tabContent class, and hide
	var $modules = $('div.module')
		.addClass('tabContent')
		.hide();

	// Create a ul before the first module; add the tabBar class
	var $nav = $('<ul/>')
		.addClass('tabBar')
		.insertBefore($modules.eq(0));

	// Iterate over the modules
	$modules.each(function() {
		var $module = $(this);
		// get the text of the first h2 for the text of an li
		var $title = $module.find('h2:first');
		var $tab = $('<li>' + $title.text() + '</li>');

		// Add the tabs class, then bind a click handler
		//   that adds current class and removes it from siblings
		//   then shows current module and hides siblings
		$tab.addClass('tabs')
			.appendTo($nav)
			.click(function() {
				$tab.addClass('current').siblings().removeClass('current');
				$module.show().siblings('.module').hide();
			});
	});
	// Triggering click handler can replace selecting first tab manually
	$nav.find('li:first').click();
	// Instead of:
	//$modules.eq(0).show();
	//$nav.find('li:first').addClass('current');
});

Please see the comments in the code. There is also a solution using data instead of closures (tabs-data.js).

Next