DEV Community

ktr92
ktr92

Posted on

[html css jquery] How to do tabs panel for switch content

Here is an example of creating a simple reusable universal tabs panel.

codepen: https://codepen.io/ktr92/pen/VwEpyyY

Result:

Image description

Solution
HTML:

<div class="tabs" data-tabs="tabs_id">
  <div class="tabs__header" data-tabsheader="tabs_id">
    <div class="active" data-tabsbutton="tabs_id">1 tab</div>
    <div data-tabsbutton="tabs_id">2 tab</div>
    <div data-tabsbutton="tabs_id">3 tab</div>
  </div>

  <div class="tabs__content active" data-tabscontent="tabs_id">
    <p>Tab 1 content</p>
  </div>

  <div class="tabs__content" data-tabscontent="tabs_id">
    <p>Tab 2 content</p>
  </div>

  <div class="tabs__content" data-tabscontent="tabs_id">
    <p>Tab 3 content</p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS (minimal, without design styling):

[data-tabscontent] {
  display: none;
}

[data-tabscontent].active {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

JS (jquery):

$(function () {
  $("[data-tabsheader]").on(
    "click",
    "[data-tabsbutton]:not(.active)",
    function () {
      $(this)
        .addClass("active")
        .siblings()
        .removeClass("active")
        .closest("[data-tabs]")
        .find("[data-tabscontent]")
        .removeClass("active")
        .eq($(this).index())
        .addClass("active");
    }
  );
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)