Click the box titles below to expand:

How to's

XSLT

GOOGLE MAPS API

PHP

Perl

Document Object Model (DOM)

UNIX

Generic Mapping Tools (GMT)

Miscellaneous

Projects

Courses Taught

Latest Favorites

Mac OS X

Web Development

Beta

How To :: Preserving state on show and hide tabs using cookies

In several projects I have used the unobtrusive show/hide CSS tabs Javascript code written by Bobby van der Sluis.

This code is great, but one thing it does not do is preserve state (i.e. which tab has been selected) on a page refresh.

I have a project where I used Bobby's code, but the pages need to refresh every 5 minutes to reflect the latest real time data our seismic network has received.

Bobby's original script did not have to account for this updating and need to preserve the selected tab, so I thought about the best way to do this in a web browser. The solution I came up with was to insert extra Javascript into Bobby's code that creates a cookie on the client-side that notes which tab has been selected. Then on a page refresh, the cookie is read and the respective tab highlighted.

Javascript Guru Peter Paul Koch has a great article about how to dynamically create, read and destroy cookies using Javascript. I believe he attributes the original script to Scott Andrew.

So, the only thing I did was to combine these two scripts. Code is below. Hopefully I have left the copyright notices intact correctly:

tabs.js

  1. // Modified from http://www.bobbyvandersluis.com/articles/unobtrusiveshowhide.php
  2. // Cookie functions, modified from http://www.quirksmode.org/js/cookies.html
  3.  
  4. if (document.getElementById && document.getElementsByTagName && document.createElement) {
  5. document.write('<style type="text/css" media="all">@import "tabs.css" ; </style>');
  6. window.onload = initShowHide;
  7. }
  8.  
  9. function initShowHide() {
  10. if (document.getElementById && document.getElementsByTagName && document.createTextNode) {
  11. var myTabs = new Array() ;
  12. var myCookie = read_cookie_tab('tab') ;
  13. var toggle = document.getElementById('tabSelector');
  14. var as = toggle.getElementsByTagName('a');
  15. hide();
  16. for( var i = 0; i < as.length; i++ ) {
  17. myTabs.push( as[i].href.match(/#(\w.+)/)[1] ) ;
  18. as[i].onclick = function() {
  19. show(this);
  20. return false;
  21. }
  22. }
  23. }
  24. // Check to see if a cookie is set, or else activate first tab by default
  25. for( var j = 0; j < myTabs.length; j++ ) {
  26. if( myCookie == myTabs[j] ) {
  27. show( as[j] ) ;
  28. return ;
  29. }
  30. }
  31. show( as[0] ) ;
  32. }
  33.  
  34. function show(s) {
  35. hide();
  36.  
  37. // Erase the current cookie
  38. erase_cookie_tab('tab');
  39.  
  40. var id = s.href.match(/#(\w.+)/)[1];
  41.  
  42. // Set a cookie to ensure reload keeps tab focus
  43. set_cookie_tab('tab',id,1) ;
  44.  
  45. document.getElementById(id).style.display = 'block';
  46.  
  47. // Try to get a reference to an element with the id 'current' (a previously active tab header)
  48. var oldCurrent = document.getElementById('current');
  49.  
  50. // If this element exists, remove its ID attribute
  51. if (oldCurrent) oldCurrent.removeAttribute('id');
  52.  
  53. // Add the ID attribute with value 'current' to the newly active tab header (LI element)
  54. s.parentNode.setAttribute('id', 'current');
  55. }
  56.  
  57. function hide() {
  58. var toggleable = document.getElementById('tabbedContent').getElementsByTagName('div');
  59. for (var i = 0; i < toggleable.length; i++) {
  60. toggleable[i].style.display = 'none';
  61. }
  62. }
  63.  
  64. function set_cookie_tab(name,value,days) {
  65. if( days ) {
  66. var date = new Date() ;
  67. date.setTime(date.getTime()+(days*24*60*60*1000));
  68. var expires = " ; expires="+date.toGMTString();
  69. }
  70.  
  71. else var expires = "";
  72. document.cookie = name+"="+value+expires+"; path=/" ;
  73. }
  74.  
  75. function read_cookie_tab( name ) {
  76. var cookieName = name + "=" ;
  77. var ca = document.cookie.split( ';' ) ;
  78. for( var i=0; i<ca.length; i++ ) {
  79. var c = ca[i];
  80. while( c.charAt(0)==' ' ) c = c.substring( 1,c.length ) ;
  81. if( c.indexOf( cookieName ) == 0 ) return c.substring( cookieName.length,c.length ) ;
  82. }
  83. }
  84.  
  85. function erase_cookie_tab(name) {
  86. set_cookie_tab(name,"",-1);
  87. }
  88.  

tabs.css

  1. #tabbedNav {
  2. float: left;
  3. width: 100%;
  4. font-size: 93%;
  5. line-height: normal;
  6. }
  7. #tabbedNav ul {
  8. margin: 0;
  9. padding: 10px 10px 0;
  10. list-style: none;
  11. white-space: nowrap ;
  12. }
  13. #tabbedNav li {
  14. float: left ;
  15. background-color: #FFF ;
  16. margin: 0 ;
  17. padding: 0 ;
  18. margin-right: 10px ;
  19. list-style: none;
  20. border: 1px solid #333 ;
  21. }
  22. #tabbedNav a {
  23. float: left;
  24. display: block;
  25. width: .1em;
  26. padding: 5px 15px 4px ;
  27. font-weight: bold;
  28. color: #8B7355 ;
  29. text-decoration: none ;
  30. }
  31. #tabbedNav > ul a {
  32. width: auto;
  33. }
  34. /* Commented Backslash Hack hides rule from IE5-Mac \*/
  35. #tabbedNav a {
  36. float: none;
  37. }
  38. /* End IE5-Mac hack */
  39. #tabbedNav a:hover {
  40. color: #900 ;
  41. border: none ;
  42. }
  43. #tabbedNav #current {
  44. background-color: #FFC ;
  45. }
  46. #tabbedContent {
  47. padding: 10px ;
  48. border: 1px solid #333 ;
  49. margin: 10px ;
  50. }
  51. #tabbedContent h3 {
  52. margin-top: 2.0em ;
  53. }
  54.  

Working code example

If you select any of the tabs below they show the selected content and hide the content of the other divs. If you hit reload then the previously selected tab will retain it selection (preserve state). This will only work if your browser is configured to accept cookies.

Tab One Content

Lorem ipso ad horem ex post in dolor et quinque gloria patri et fili et spiritus est. Ad quorum sunt corpus ad beneditus fructus gratia plena dominus tecum ...

Tab Two Content

Lorem ipso ad horem ex post in dolor et quinque gloria patri et fili et spiritus est. Ad quorum sunt corpus ad beneditus fructus gratia plena dominus tecum ...

Tab Three Content

Lorem ipso ad horem ex post in dolor et quinque gloria patri et fili et spiritus est. Ad quorum sunt corpus ad beneditus fructus gratia plena dominus tecum ...

Tab Four Content

Lorem ipso ad horem ex post in dolor et quinque gloria patri et fili et spiritus est. Ad quorum sunt corpus ad beneditus fructus gratia plena dominus tecum ...

Tab Five Content

Lorem ipso ad horem ex post in dolor et quinque gloria patri et fili et spiritus est. Ad quorum sunt corpus ad beneditus fructus gratia plena dominus tecum ...

Disclaimer

This information is freely provided as–is. Messing around with the command line and creating files is a serious business, and I accept no liability for errors created, systems corrupted, or hard–disk damage by you following these instructions. They worked for me but may not work for you. Remember to back–up EVERYTHING before you try any of this stuff — it is not simple OR easy!!!

If you have any questions about this please email me at rlnewman@ucsd.edu and I will try my best to help you out.

made with CSS     Valid XHTML 1.0!      Valid CSS!