How to build simple tabs with jQuery?

前端 未结 6 741
感动是毒
感动是毒 2020-11-29 02:58

I have the following code: fiddle

Which works great in websites I create my self and with no JS the tabs act as jump links to the relevant sections. When placed in

6条回答
  •  萌比男神i
    2020-11-29 03:35

    Solution JSFiddle:: https://jsfiddle.net/incorelabs/mg6e4ren/74/

    Implementing Tabs is really simple, I have modified the HTML for your question a bit. Removed the anchor tags coz they are not needed.

    HTML

    • Tab 1
    • Tab 2
    • Tab 3
    • Tab 4
    Some content for Tab - 1

    HTML De-Mystified

    1. Add the "tab-switcher" class to each "li" element as well as tabindex="0" to make it accessible.
    2. Give a "data-tab-index" attribute to each "li".
    3. Add the "tab-container" class to each Tabbed Container. Also provide a "data-tab-index" attribute to each container which corresponds to the "data-tab-index" attribute on the "li" element.
    4. Show only the container you want visible, hide the others using "display:none".
    5. Provide a parent container for all the content of the tabbed containers. In this example this is the "allTabsContainer" div.

    jQuery

    $(document).ready(function () {
        var previousActiveTabIndex = 0;
    
        $(".tab-switcher").on('click keypress', function (event) {
            // event.which === 13 means the "Enter" key is pressed
    
            if ((event.type === "keypress" && event.which === 13) || event.type === "click") {
    
                var tabClicked = $(this).data("tab-index");
    
                if(tabClicked != previousActiveTabIndex) {
                    $("#allTabsContainer .tab-container").each(function () {
                        if($(this).data("tab-index") == tabClicked) {
                            $(".tab-container").hide();
                            $(this).show();
                            previousActiveTabIndex = $(this).data("tab-index");
                            return;
                        }
                    });
                }
            }
        });
    });
    

    jQuery De-Mystified

    1. The click and keypress listener on the "tab-switcher" gets initialized on "document.ready". (Note: The keypress only registers the "Enter" key)
    2. The variable "previousActiveTabIndex" keeps a track of the previous active tab so that if we press on the same tab again and again, it can be ignored.
    3. We run an EACH loop on the "tab-container". This is done to know which tab should be displayed. If the "data-tab-index" data attribute on each matches, we display that tab.
    4. We keep the value of the "data-tab-index" saved in "previousActiveTabIndex" which helps us keep a track of the previous tab which was clicked.

    If there are doubts or if someone has suggestions, do comment on the post.

提交回复
热议问题