PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 2, How Prototype Extends Elements

Showing and Hiding Elements

The final element extensions we are going to look at in this article are the methods using for hiding and showing elements. Using hidden elements is a useful technique for creating pages that react quickly to user interaction. One example of this is with dropdown sub-menus that only appear when the mouse hovers over a main menu item.

There are three methods involved with this, each of which accepts no arguments when called.

  • hide(): This method will hide an element from the display.
  • show(): This method will show an element that has been hidden.
  • toggle(): This method will show a hidden element, or hide a visible element.

One extremely important point when using these methods is that if you want to show a hidden element (using either show() or toggle()), the element must not have been hidden via a CSS stylesheet.

That is, if you want to initially hide an element, you must use an inline style attribute that includes display: none.

Listing 17 shows a few basic examples of using each of these methods.

Listing 17 Showing and hiding elements with hide(), show() and toggle() (listing-17.html)
<html>
    <head>
        <title>Showing and hiding elements with hide(), show() and toggle()</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="a">
            This box will start visible but become hidden
        </div>
 
        <div id="b" style="display:none">
            This box will start hidden and become visible
        </div>
 
        <div id="c">
            This box will be visible, then become hidden, the appear again
        </div>
 
        <script type="text/javascript">
            $('a').hide();
            $('b').show();
 
            var c = $('c');
            c.toggle();
            c.toggle();
        </script>
    </body>
</html>

While including inline style tags is not desirable (and is specifically one of the things you want to avoid when creating neat and tidy markup), unfortunately it is required in this particular situation. This is a drawback not of Prototype, but in how CSS and JavaScript work together.

To get around doing this you must do one of the following for each of the elements you want to be hidden to begin with:

  • Show the elements initially and use JavaScript to hide them once the page loads.
  • Create the elements dynamically and insert them into the DOM as hidden elements.

Note that the second suggestion here is not necessarily desirable since creating elements in real-time may affect the accessibility of your page.

In This Article