Layered navigation, for our purposes, requires the user to click an element, which then displays the next set of elements, until the user selects a specific option which displays new content. This becomes useful when dealing with multiple categories and sub-categories of options. The default behavior is often to link each category and sub-category with the next set of options, which requires a page load with each selection. Using jQuery we can create a layered navigation that does not reload the page until a final option is selected.
In this tutorial our HTML will consist of a
<nav> element that contains several
<div> elements. We will also include an outer
<div> element that creates a button to reset our menu.
Some things to note here:
- We have given all
<div>s within the
<nav>element a class of
- We have also given the first
<div>a class of
.main, this will be the main element that shows up when our page is first loaded.
- The next three
<div>s have a class of
.sectionwhich will be used to display them when the main element is clicked. They also each have a unique class (
.tertiary-section) which will be used to display specific elements when they are clicked.
- All of the rest of the elements have a class that is shared with the others in its group (
.tertiary) and a unique class for that element’s color.
The main CSS to pay attention to here is on the outer
As commented in the code, you will need to set the
#layered-nav element to
display: flex and
flex-flow: row wrap.
If you choose to not use flex-box you will need to set a specific
#layered-nav and set the
.option class to
$(document).ready(). Then we will set the
.click() behaviors for all elements (including our reset button) and call it a day.
As you can see, we are mostly just making use of jQuery’s built-in
First, we built the
hideAll() function and just set all elements with the
.option class to
.hide(). We will use this
We set the navigation’s default behavior using
$(document).ready(). First, on page load, we hide all of the elements using
hideAll(), then we display the
.main element using
Lastly, we define the
.click() behavior for all elements. We will begin each
.click() function with our
hideAll() function to remove all the elements, then we will use
.show() to display each section of elements by selecting the appropriate class (
.section for the three sub-sections, and
.tertiary for the final tier of options)
The final project output will look and function similar to this: