Indeed, the function itself is quite simplistic. Letís analyze in turn each section in order to get a good understanding about what they do. The script starts getting the "navbar" and "content" <div> elements from the page, since they will be manipulated later. Then, a new <div> element is created in memory, named "swbar." This is our switcher bar, mentioned above, which is assigned the selector "swicther" in order to apply the correct style. Also, a "title" attribute is added to the bar, to show initially the text "hide bar," indicating to the user that the sidebar can be hidden. The code section that performs these tasks is the following:
Next, the "switcher" <div> element is inserted into the document by locating the content node and then appending the element before to it, in the document tree. Using the DOM, itís quite easy to do:
Now, the "switcher" bar has been inserted in the correct place within the page. The next step is to enable it to hide and display accordingly the "navbar" element. This is pretty easy to do by assigning an "onlclick" event handler to our "switcher" bar and setting the "navnar" elementís display property to "none" and "block," alternately. Letís take a look at the code block that accomplishes the task:
As part of the switching process, the "backgroundImage" property is manipulated too, for displaying a different background image each time the bar is clicked on. To do this, Iíve used "tab_left.gif" and "tab_right.gif" background images respectively, as you can see in the script. Of course, you can use the images that best suit your needs, or even apply an entirely different style. Additionally, the "title" attribute is changed according to the state of the "navbar" element. If itís visible, the value will be "hide nav." Otherwise, the assigned value will be "show nav."
Wrapping the whole code into a generic function gives us more flexibility when we have multiple scripts that need to be executed when the page has been loaded. Using a single "window.onload" statement, only the last script attached will be executed. Another good approach to solving this problem involves the use of the "addEventListener" or "attachEvent()" methods, depending on which browser weíre dealing with. How this kind of dynamic event attachment should be handled is the subject of another article.
Back at our example, weíve created a simple script that plays with the CCS "display" property to hide and show the side navigation bar. In the next section, weíll see the full code for this example, as well as some handy images to illustrate the functionality of this technique.