Basic Tabs in Javascript

Introduction: This tutorial is on how to create simple, small tabs in Javascript. When I say 'small tabs', I mean that this shouldn't be used for tabs holding large amounts of content. HTML: First we want to create a text area in which we are going to be holding the tab content...
  1.         <head>
  2.         </head>
  3.         <body>
  4.                 <textarea id='area'></textarea>
  5.         </body>
  6. </html>
Then we want a few buttons to act as options to change the current tabs. We simply parse the tab number to the function 'update'...
  1.         <head>
  2.         </head>
  3.         <body>
  4.                 <textarea id='area'></textarea>
  5.                 <button onclick='update(1);'>1</button>
  6.                 <button onclick='update(2);'>2</button>
  7.                 <button onclick='update(3);'>3</button>
  8.         </body>
  9. </html>
Javascript: Now we want to create a couple of Javascript variables. First we want an integer named 'indexid' to hold the current tab index/number. And we also want an array of strings which contain the tabs content, we'll name this 'values'...
  1.         <head>
  2.                 <script>
  3.                         var indexid = 0;
  4.                         var values = new Array("one", "two", "three", "four");
  5.                 </script>
  6.         </head>
  7.         <body>
  8.                 <textarea id='area'></textarea>
  9.                 <button onclick='update(1);'>1</button>
  10.                 <button onclick='update(2);'>2</button>
  11.                 <button onclick='update(3);'>3</button>
  12.         </body>
  13. </html>
Finally we want to make our 'update' function. We want to accept one parameter which is the new tab id. We then set the variable holding the current tab id ('indexid') to the new 'id' parsed value, and update the text of our textarea with the id of 'area' with the new tabs content - we simply pull this from our 'values' string array at the element index of the parsed 'id' value to the function...
  1.         <head>
  2.                 <script>
  3.                         var indexid = 0;
  4.                         var values = new Array("one", "two", "three", "four");
  5.                         function update(id) {
  6.                                 indexid = id;
  7.                                 document.getElementById('area').value = values[indexid];
  8.                         }
  9.                 </script>
  10.         </head>
  11.         <body>
  12.                 <textarea id='area'></textarea>
  13.                 <button onclick='update(1);'>1</button>
  14.                 <button onclick='update(2);'>2</button>
  15.                 <button onclick='update(3);'>3</button>
  16.         </body>
  17. </html>

Add new comment