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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay