Tabs jQuery plugin

15.04.19

Tabs are a fairly common element. There are various implementations of this element on the Internet. But often the tabs are overloaded with code filled with effects that are unlikely to be needed in ordinary tasks. Therefore, it was decided to write simple tabs, so to speak, “for myself”. Maybe they will be useful to someone else.

Tabs can be downloaded from GitHub. Tabs do not have any effects, but directly fulfill their purpose - hide and display.

HTML

<!--Installation-->
<head>
     <script src="/jquery.js"></script>
     <script src="/simpletabs.js"></script>   
</head>
<!-- //-->
<div class="tabsblock">
     <div class="headertabs">
          <div class="nametab actheadtab">Tab 1</div>
          <div class="nametab">Tab 2</div>
          <div class="nametab">Tab 3</div>
     </div>
     <div class="tabswr">
          <div class="contenttab activetab">
               Contents of the first tab
          </div>
          <div class="contenttab">
               Contents of the second tab
          </div>
          <div class="contenttab">
               Contents of the second tab
          </div>
     </div>
</div>

CSS

.contenttab{
     display: none; /* hide contents of the tabs*/
}
.contenttab.activetab{
     display: block; /*display contents of the active tab*/
}

Initialization

$(function(){

   $('.tabsblock').simpleTabs();
     
});

You can also use other selectors instead of default ones. It is possible to call a callback when clicking.

Initialization with options

$(function(){

   $('.tabsblock').simpleTabs({

     'title' : '.othernametab', // tab title selector
     'content': '.othercontenttab', // tab content selector
     'cb': callbackFunctionName // callback function

   });
     
});

An anonymous function can be called as a callback.

Plugin

(function($){

    $.fn.simpleTabs = function (options) {

        var settings = $.extend({
            'title' : '.nametab', 
            'content': '.contenttab',
            'cb': ''
        }, options);

        var nametab = $(this).find(settings.title), // tab title selector
            contenttab = $(this).find(settings.content), // tab content selector
            callback = settings.cb,
            tabsBlock = this;
        nametab.on('click', function () {
            var activeClass = $(this).hasClass('actheadtab'); // is the tab title active?
            if (!activeClass) {
                var ind = $(this).index();
                $(tabsBlock).find('.actheadtab').removeClass('actheadtab');
                $(this).addClass('actheadtab');
                $(tabsBlock).find('.activetab').removeClass('activetab');
                contenttab.eq(ind).addClass('activetab');
                if (callback) {
                    callback();
                }
            }
        });
    };

})(jQuery);

Demo

Tab 1
Tab 2
Tab 3
Contents of the first tab
Contents of the second tab
Contents of the third tab
blog comments powered by Disqus