JSFiddle - React, Tailwind, and code Playground

by nabeezy

HTML

<ul>
    <li class="tabs">one</li>
    <li class="tabs">two</li>
    <li class="tabs">three</li>
    <li class="tabs">four</li>
</ul>

<div class="content">ONE</div>
<div class="content">TWO</div>
<div class="content">THREE</div>
<div class="content">FOUR</div>
<button onclick="bindSets('tabs','active','content','hidden')">BIND THEM</button>

CSS

.active{
    background-color:#5555aa;
}

.hidden{
    /*display:none;*/
    background-color:#33aa33;
}

JavaScript

bindSets = function (tabClass, tabClassActive, contentClass, contentClassHidden) {
        //Dependent on jQuery
        //PARAMETERS
        //tabClass: 'the class name of the DOM elements that will be clicked',
        //tabClassActive: 'the class name that will be applied to the active tabClass element when clicked (must write your own css)',
        //contentClass: 'the class name of the DOM elements that will be modified when the corresponding tab is clicked',
        //contentClassHidden: 'the class name that will be applied to all contentClass elements except the active one (must write your own css)',
        //MUST call bindSets() after dom has rendered

        var tabs = $('.' + tabClass);
        var tabContent = $('.' + contentClass);
        if(tabs.length !== tabContent.length){console.log('JS bindSets: sets contain a different number of elements')};
        tabs.each(function (index) {
            this.matchedElement = tabContent[index];
            $(this).click(function () {
                tabs.each(function () {
                    this.classList.remove(tabClassActive);
                });
                tabContent.each(function () {
                    this.classList.add(contentClassHidden);
                });
                this.classList.add(tabClassActive);
                this.matchedElement.classList.remove(contentClassHidden);
            });
        })
        tabContent.each(function () {
            this.classList.add(contentClassHidden);
        });
    }