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.


$(document).ready(function() {
	// Find all the modules, add the tabContent class, and hide
	var $modules = $('div.module')

	// Create a ul before the first module; add the tabBar class
	var $nav = $('<ul/>')

	// 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
			.click(function() {
	// Triggering click handler can replace selecting first tab manually
	// Instead of:

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