jQuery Tabbed Element


/ Published in: JavaScript
Save to your folder(s)

jQuery Tabbed Element (CSS Not Included)


Copy this code and paste it in your HTML
  1. <!-- HTML Markup Tabbed Element -->
  2. <div id="tabs">
  3. <ul id="tab_nav">
  4. <li><a href="#tab1">Tab1 Title</a></li>
  5. <li><a href="#tab2">Tab2 Title</a></li>
  6. </ul>
  7. <div id="tab_contents">
  8. <div id="tab1" class="tab_content"><!-- Content here --></div>
  9. <div id="tab2" class="tab_content"><!-- Content here --></div>
  10. </div>
  11. </div>
  12.  
  13. /* jQuery Tabbed Element
  14.   - Avoid anonymous functions on load
  15.   - $.fn.find with Id uses native document.getElementById()
  16.   - $.fn.delegate eliminates the need for wasted selection
  17.   - Cache selectors for optimisation
  18. */
  19. var tabs = {
  20. init: function(){
  21. var $tab_contents = $('#tab_contents'), $tab_nav = $('#tab_nav');
  22. $tab_contents.find('div.tab_content:not(:first)').hide();
  23. $tab_nav.find('li:first').addClass('active');
  24. $tab_nav.delegate('li a', 'click', function(e){
  25. var activeTab = $(this).attr('href');
  26. $tab_nav.find('li').removeClass('active');
  27. $(this).parent().addClass('active');
  28. $tab_contents.find('div.tab_content').hide();
  29. $tab_contents.find(activeTab).fadeIn(250);
  30. e.preventDefault();
  31. });
  32. }
  33. }
  34. $(document).ready(tabs.init());

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.