jQuery Tabbed Element for multiple elements


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

A clean and simple jQuery function for creating a tabbed element. This one allows multiple tabbed elements on 1 page (which has been the downfall of so many others)


Copy this code and paste it in your HTML
  1. var tabs = {
  2. init: function(){
  3. var $tab_contents=$('.tab-contents'), $tab_nav=$('.tab-nav');
  4. $tab_contents.find('.tab-content:not(:first)').hide();
  5. $tab_nav.find('li:first').addClass('active');
  6. $tab_nav.on('click', 'li a', function(e){
  7. e.preventDefault();
  8. var $this=$(this),activeTab=this.hash,parent=$this.parents('section'),$contents=$(parent,$tab_contents);
  9. $(parent,$tab_nav).find('li').removeClass('active');
  10. $this.parent().addClass('active');
  11. $contents.find('.tab-content').hide();
  12. $contents.find(activeTab).fadeIn(250);
  13. });
  14. }
  15. };
  16. $(document).ready(tabs.init());
  17.  
  18.  
  19. <section>
  20. <h2>Section Title</h2>
  21. <ul class="tab-nav">
  22. <li><a href="#tab1" title="">Tab 1</a></li>
  23. <li><a href="#tab2" title="">Tab 2</a></li>
  24. </ul>
  25. <div class="tab-contents">
  26. <div id="tab1" class="tab-content"><!-- Tab 1 content here --></div>
  27. <div id="tab2" class="tab-content"><!-- Tab 2 content here --></div>
  28. </div>
  29. </section>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.