Pure JavaScript tabbing functionality with linkable tabs

on in Blog, JavaScript DOM, JavaScript Pagination
Last modified on

You can find JavaScript tabs anywhere, but only 5-10% of those are physically linkable. The script below shows you how to create such tabs without any JavaScript library.

See a Codepen demo for the complete code (HTML + CSS).

var tabLinks = document.querySelectorAll('.whiskey-tabs li a');

for (var i = 0; i < tabLinks.length; i++) {
    tabLinks[i].onclick = function() {
        var target = this.getAttribute('href').replace('#', '');
        var sections = document.querySelectorAll('.whiskey-tab-content');

        for (var j=0; j < sections.length; j++) {
            sections[j].style.display = 'none';
        }
        document.getElementById(target).style.display = 'block';

        for (var k=0; k < tabLinks.length; k++) {
            tabLinks[k].removeAttribute('class');
        }

        this.setAttribute('class', 'is-active');

        return false;
    }
}

// Enable link to tab
var hash = document.location.hash;
if (hash) {
    document.querySelectorAll('.whiskey-tabs li a[href="' + hash + '"]')[0].click();
}

See the Pen Pure JavaScript tabbing functionality with linkable tabs by Ciprian (@ciprian) on CodePen.

The compressed code is highly efficient and adds no load to your application:
305 bytes gzipped (506 bytes uncompressed)

for(var b=document.querySelectorAll(".whiskey-tabs li a"),c=0;c<b.length;c++)b[c].onclick=function(){for(var a=this.getAttribute("href").replace("#",""),e=document.querySelectorAll(".whiskey-tab-content"),d=0;d<e.length;d++)e[d].style.display="none";document.getElementById(a).style.display="block";for(a=0;a<b.length;a++)b[a].removeAttribute("class");this.setAttribute("class","is-active");return!1};var f=document.location.hash;f&&document.querySelectorAll('.whiskey-tabs li a[href="'+f+'"]')[0].click();

Find more JavaScript tutorials, code snippets and samples here.

Related posts