Docstoc

CSS create collapsible tables

Document Sample
CSS create collapsible tables Powered By Docstoc
					         .net technique css




         C c
         CSS create
        collapsible tables
         Craig Grannell shows you a nifty technique to collapse the body area of
                     ell
                                                                                                                                                           Your essentia s
                                                                                                                                                                     m thi
                                                                                                                                                           All the code fro
                                                                                                                                                           month’s tutori
                                                                                                                                                           found on this
                                                                                                                                                                         l CD
                                                                                                                                                                          al can be
                                                                                                                                                                          issue’s CD.



         website tables, using a combination of CSS and JavaScript

          Knowledge needed Intermediate CSS, JavaScript and HTML
                                                                                               Expert tip Multiple bodies
          Requires Text editor
                                                                                                 Although it’s not something that’s commonly done, it’s possible to
          Project time 20 minutes
                                                                                                 add multiple table bodies to a single table (all of them must be placed
                                                                                                 after the table footer in the code). By utilising the methods shown in
                    It’s generally recommended you ensure the vast majority of your
                                                                                                 the tutorial and injecting a little imagination, this opens up all sorts of
                    web page content is immediately visible when someone accesses it
                                                                                                 possibilities for tables. For example, you could, by default, show a top
                    – but there are exceptions. For example, you might want to provide
                                                                                                 10 chart, and then use the toggle link to expand the table to a top 40.
         access to some historical information but not clutter up the page with
                                                                                                 Just ensure you amend your JavaScript to suit, to target the relevant
         several years’ worth, which might distract users.
                                                                                                 tbody element.
             This kind of thing often happens with tables. You might have a sports table
         or a favourites chart and want to provide the potential for comparison, but
         only initially display the most recent table’s content. This tutorial provides a
         simple and elegant solution for doing just that, utilising JavaScript and CSS to     (and also potentially enable all sorts of browser ‘tricks’, such as scrolling
         create collapsible tables.                                                           the body while leaving the head and foot in place) and group components,
             The concept behind the methodology of this month’s tutorial isn’t new,           thereby enabling a section to be targeted and collapsed.
         and closely resembles a tutorial we did in issue 169, which detailed how to              If you take a look at table.html on the CD, you’ll see an example of such a
         work with the DOM (Document Object Model) tree to modularise collapsible             table. This is a simple three-column table that lists some audio track names,
         content. The idea was to use clickable headings to toggle the visibility of the      along with their related artist and album. (Note that this code is also based
         subsequent block element: a div. With pages or page areas that have a very           on a previous .net column, and the original can again be found online: see:
         strict structure, this kind of manipulation is faster and more efficient code-       www.netmag.co.uk/zine/develop-css/produce-perfect-tables).
         wise than targeting from each link an element with a specific id value. (Note:           Reduced to its basic structural components, the table looks like the
         the full tutorial from issue 169 is online at www.netmag.co.uk/zine/develop-         following code block.
         css/sort-out-your-drawers, so visit our website if you missed it.)
             Although tables haven’t traditionally leant themselves to this kind of           <table>
         manipulation, due to basically being a bunch of row elements, that all                <caption></caption>
         changes when row groups are added to the mix. The three row group                     <thead></thead>
         elements – thead, tbody and tfoot – provide a logical structure to a table            <tfoot></tfoot>
                                                                                               <tbody></tbody>
                                                                                              </table>

                                                                                              Note that the order in the previous code is correct: head, foot, body. This
                                                                                              enables browsers to render the table’s foot prior to receiving all the table’s
                                                                                              data. However, browsers then correctly display the row groups in the order
                                                                                              you’d expect: head, body, foot.

                                                                                              Technological concerns
                                                                                              To move from a flat table to a collapsible one, a number of things need to
                                                                                              be taken into account, such as how the interaction is going to work, which
                                                                                              technologies are going to be used for various tasks, and what’s going to
                                                                                              happen if certain technologies aren’t available – notably JavaScript.
                                                                                                  First: interaction. There needs to be some way of toggling the table body’s
                                                                                              visibility (which effectively results in the table ‘opening’ and ‘closing’). A link in
                                                                                              the table footer is a logical device for achieving this. In terms of technologies,
                                                                                              a combination of JavaScript and CSS is generally used for drawers, with
                                                                                              JavaScript being used to toggle the display CSS property (and thereby
                                                                                              the visibility) of the element comprising the drawer’s ‘content’. Therefore,
                                                                                              JavaScript will be used to change the display value of the tbody element,
                                                                                              which will initially be none, so the table starts life collapsed.
         Table tweaks Here you can see both the collapsed and expanded table. Also note the       That last point then triggers an accessibility problem for users who don’t
         rollover effect on the table’s footer, which lightens the entire container           have JavaScript enabled: without scripting, the table remains firmly shut.



         72     .net march 2009




NET186.tut_css 72                                                                                                                                                                       14/1/09 12:35:15 pm
                                                                                                                                                     .net technique css

              Therefore, logically, the default value of the tbody element actually has to
              make it visible; the none value should only be applied if JavaScript is enabled.
              This can be done by using JavaScript to attach an override style sheet.                    Find targets on a page
                  If we do a quick ‘skip to the end’, the results of this thinking through and
              the subsequent answers are shown in collapsible-tables.html and its related                Use a JavaScript alert to hone in on your
              files. Open the document in a web browser and you’ll see the same table                    desired element for toggling
              caption and table head as earlier, but the table body isn’t visible. The footer,
              rather than being empty, now has a ‘toggle table content’ link, along with an              Once you have the basic method of this month’s tutorial inserted
              inviting downwards-facing arrow. Click the link (the entire footer is effectively          into your brain and an example of the code happily nestled in your
              an active area), and the table body is shown; furthermore, the downwards-                  boilerplates folder, the hardest part in implementing it in new sites is
              facing arrow changes to an upwards-facing one, in order to display what will               figuring out the path from link to target.
              happen to the table body when the footer link is next clicked.                                To confirm the target from a path you’ve defined, give your link
                                                                                                         a unique id value of linkToggler and then add the following script
                                                                                                         somewhere below the link on your web page.
                Three row group elements –                                                               <script type=”text/javascript”>
                thead, tbody and tfoot –                                                                 //<![CDATA[
                                                                                                         alert(document.getElementById(“linkToggler”).nodeName);

                provide a logical structure                                                              //]]>
                                                                                                         </script>

                 If you disable JavaScript in whatever browser you’re using and reload the               Prior to .nodeName, add relevant JavaScript properties (.nextSibling,
              page, you’ll see that the table displays in full, with a couple of exceptions. First,      .parentNode, etc). On loading the web page, an alert will detail the
              the horizontal stripes are driven by JavaScript, so they aren’t displayed. Secondly,       target element, based on the defined path. Using an alert is particularly
              the footer link is irrelevant for browsers that have JavaScript disabled, and so           handy for sanity
              said link is removed (to avoid people clicking it and nothing happening).                  checking targets
                                                                                                         when browsers
              Under the hood                                                                             disagree about their
              The majority of the HTML and CSS is pretty straightforward, and differs                    locations and what
              little from the table tutorial mentioned earlier. In the mark-up, the only                 represents undefined
              major important addition outside of the head section linking to various                    content, enabling you
              dependencies is the table footer, which now includes a link to trigger a                   to rapidly figure out
              JavaScript function. An identical link can be used in other similarly structured           an override path.
              tables to drive the same kind of toggle.
                                                                                                        Stay alert If you’re
               <tfoot>                                                                                  having trouble figuring
                <tr>                                                                                    out which element
                 <td colspan=”3”><a href=”#” onclick=”toggle(this); return false;”>Toggle               you’re targeting, use
                                                                                                        a JavaScript alert
               table content</a></td>
                </tr>
               </tfoot>

              In the main CSS file, collapsible-tables.css, the things to look out for are            set to not display at all, as mentioned earlier. At this point, we need to make a
              the default styles for the tbody element and the link in the table footer.              brief aside.
              Remember, these are the defaults for when JavaScript is disabled.                            As is often the case, Internet Explorer throws a quick curveball directly
                                                                                                      to the face. It doesn’t understand table-row-group, but, luckily, it seems to
               tbody {                                                                                render the page correctly if the value block is used instead. Because this value
               display: table-row-group;                                                              screws things up in every other browser, it’s applied as an IE-specific override
               }                                                                                      via a conditional comment.
               tfoot a {                                                                                   Back to our main programme, and the tbody and table footer link styles
               display: none;                                                                         for JavaScript-enabled browsers have been added to a separate style sheet,
               }                                                                                      js-override.css. This sets the default display value of tbody to none, thereby
                                                                                                      making the table collapsed when the page is first opened. It also adds a bunch
              As you can see, tbody has a display value of table-row-group, which specifies           of styles to the footer link, setting it to display as a block element (thereby
              that it displays as an element that groups one or more rows. The footer link is         filling its container, the table footer) and defining the down-arrow image as its
                                                                                                      background. A third rule, tfoot a:hover, changes the background colour of the
                                                                                                      link on the hover state, making it more obvious that it’s a clickable element.

                                                                                                      tbody {
                                                                                                      display: none;
                                                                                                      }
                                                                                                      tfoot a {
                                                                        Examples Functionality        display: block;
                                                                        for this tutorial is mainly   text-decoration: none;
                                                                        drawn from our earlier        text-transform: uppercase;
                                                                        modular drawers piece. The    color: #000000;
                                                                        examples demonstrate how
                                                                        simple, modular code can
                                                                                                      padding: 4px 0;
                                                                        be used for very different    background: url(down-arrow.gif) 5px 60% no-repeat;
                                                                        layout components             }



                                                                                                                                                   .net march 2009        73        next>




NET186.tut_css 73                                                                                                                                                               14/1/09 12:35:15 pm
         .net technique css

                                                                                            Left Without JavaScript,
                                                                                            the table still displays.
                                                                                            Toggling scripts/
                                                                                            styles often omit this
                                                                                            functionality, making
                                                                                            content inaccessible
                                                                                            for many users




                                                                                            Right It’s vital to use
                                                                                            the correct display value.
                                                                                            Here’s what happens to
                                                                                            our page in Firefox when
                                                                                            it’s fed block for the tbody
                                                                                            element display value


                    tfoot a:hover {                                                         function toggle(toggler) {
                    background-color: #eeeeee;                                               if(document.getElementById) {
          }                                                                                  imageSwitch = toggler;
                                                                                             targetElement = toggler.parentNode.parentNode.parentNode.nextSibling;
         Exploring the script                                                                if(targetElement.className == undefined) {
         The toggle functionality is driven by some of the contents of the JavaScript          targetElement = toggler.parentNode.parentNode.parentNode.nextSibling.
         document collapsible-tables.js. However, the first chunk of code in the script     nextSibling;
         is used to attach the override CSS (js-override.css). Note that this might look     }
         long-winded, but it’s compliant, unlike document.write, which should be
         avoided if you’re intent on using modern methods.                                  The final part of a switching script is usually a simple if/else statement that
                                                                                            determines whether an element’s in its default state. If it is, it’s set to its
          var cssNode = document.createElement(‘link’);                                     alternate state; if not, it’s set to its default state. With the likes of a div drawer,
          cssNode.setAttribute(‘rel’, ‘stylesheet’);                                        these values are usually none and block – in other words, if upon the function
          cssNode.setAttribute(‘type’, ‘text/css’);                                         being triggered a div’s display setting is none, it’s set to block, otherwise it’s
          cssNode.setAttribute(‘href’, ‘js-override.css’);                                  set to none.
          document.getElementsByTagName(‘head’)[0].appendChild(cssNode);                        In the case of our example, the varying requirements of Internet Explorer
                                                                                            and all other browsers mean an additional step is needed. First, a variable
         When the table footer link on the web page is clicked, two things must             needs creating to define the alternate CSS display value used to expand the
         happen: the arrow image should switch, and the visibility of the tbody             list – block for Internet Explorer and table-row-group for everything else.
         element has to toggle. Each target is defined via the toggle function.
            For the arrow image, this is simple: the image is a background on the           if (navigator.userAgent.indexOf(‘IE’)!= -1) {
         table footer link, and so there’s no path to define: style updates are therefore   var displaySetting = “block”;
         applied to the element that was clicked, denoted by toggler. However,              }
         to target the tbody element, a path along the DOM tree is defined using            else {
         JavaScript properties.                                                             var displaySetting = “table-row-group”;
            Figuring out the target path is largely a logical process, using the            }
         parentNode property to go up one level in the document hierarchy (for
         example, from td to tr) and nextSibling to access the next child node of           This value is then used in the aforementioned if/else statement. Said
         a parent. Some browsers count white space as the next sibling, hence the           statement effectively reads: if the display value of the target tbody element
         addition of another line to the script that hurries said browsers on to the        is block (for IE) or table-row-group (for everything else), set it to none and
         subsequent sibling.                                                                display the down-arrow image; otherwise, set display to block (for IE) or
                                                                                            table-row-group (for everything else) and display the up-arrow image.

              Resources Where to find more                                                   if (targetElement.style.display == displaySetting)
                                                                                               {
                                                                                               targetElement.style.display = “none”;
                                                                                               imageSwitch.style.backgroundImage = “url(down-arrow.gif)”;
                                                                                               }
                                                                                               else
                                                                                               {
                                                                                               targetElement.style.display = displaySetting;
                                                                                               imageSwitch.style.backgroundImage = “url(up-arrow.gif)”;
                                                                                               }
                                                                                               }
              Past tutorials                       CSS support                              }
              If you’ve missed previous .net       It’s hardly a huge shock when
              tutorials, such as those             you have to hack in some                                         About the author
              mentioned elsewhere in this          CSS workarounds for Internet
                                                                                                                   Name Craig Grannell
              article, head over to our website,   Explorer, but reduce the surprise
                                                                                                                   Site www.snubcommunications.com
              which provides online reprints       by checking out the CSS browser
              and downloadable PDFs of             support chart at Web Devout.                                    Areas of expertise Information architecture, site concepts,
              previous columns.                    www.webdevout.net/browser-                                      graphics, interface and front-end design
              www.netmag.co.uk/zine/develop        support-css                                                     Clients Swim~, Rebellion, IDG
                                                                                                                   How do you like your eggs? Cooked



         <prev       74    .net march 2009




NET186.tut_css 74                                                                                                                                                                14/1/09 12:35:16 pm

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:240
posted:1/31/2011
language:English
pages:3