Collapsible Navigation Bars with CSS and JavaScript
In this first part of a four-part series, I will show you how to build a dynamic navigation bar that can be turned on and off by means of a simple switcher. This small web application will combine some JavaScript code, a few CSS styles and basic markup.
Collapsible Navigation Bars with CSS and JavaScript - Adding behavior to the previous navigation bar (Page 3 of 4 )
As you read in the previous section, it's pretty simple to develop a small JavaScript application that turns the static navigation bar that I built earlier into a dynamic element, which can be hidden and shown alternatively on a web page.
The JavaScript program that I plan to develop in the next few lines will be comprised of two main functions. The first one will be tasked with creating on the fly a simple "switcher," which will come in useful for hiding and displaying the navigation bar in question. The second one will hide it when the web page has been loaded.
Now it's time to get rid of this boring theory and show you how these JavaScript functions look, so you can have a clear idea of what they do. Here they are:
All right, now that you saw how the two previous JavaScript functions look, let me explain to you how they work. First, the "hideNavBar()" function will do precisely what it suggests: hide the navigation bar from the web page after it has been loaded.
As you can see, this simple process is performed by assigning a "hidden" CSS class to the navigation bar, which only includes a "display: none" declaration. Still with me? Okay, now it's time to take a look at the "createSwitcher()" function.
In this case, this function uses some DOM methods to dynamically create a simple switcher, which will be responsible for turning the pertinent navigation bar on and off. Of course, it's also necessary to list the definition of the "hidden" CSS class, so you can grasp how the pieces fit together, so here it is:
.hidden{
display: none;
}
That was really simple, right? But, wait a minute! Did you realize how much has been done with a couple of JavaScript functions and a simple CSS class? I bet you did, but anyway let me put it in plain terms: at this point, I developed a small JavaScript application that shows and hides the previous navigation bar using a basic switcher, without sacrificing its original functionality. Besides, it's worthwhile to notice that the navigation bar remains completely functional even if scripting is disabled on the browser.
Nevertheless, the prior JavaScript application looks rather disarticulated in its current incarnation, since it's necessary to link it to the structural markup that you saw in the previous section.
Therefore, in the section to come I'll be putting all the pieces together, thus completing the development of this dynamic navigation bar.