【jQuery】タブを効率良く作ってみる(複数設置、プラグインなし)

デザオ
1ページにタブを3個くらい置きたいのですがー
デザコト
おー、なるほどー。じゃあ、プラグインなしで作ってみますねー

とりあえずタブを1個作ってみる(プラグインなし)

今回のテーマ。

  • roleとaria-expandedを使ってタブが切り替わるようにしてみよう。
  • keyCodeの指定もしておこう。
コードを見る(HTML・CSS・jQuery)

HTML

<div class="u-tab">
  <ul class="u-tab__menu" role="tablist">
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="true"><span class="u-tab__item-main">タブ1</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ2</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ3</span></a>
    </li>
  </ul>
  <div class="u-tab__body u-block" role="tabpanel" aria-expanded="true">タブ1のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ2のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ3のこと</div>
</div>

CSS

.u-tab__menu {
  display: flex;
  align-items: flex-end;
  margin-right: -1rem;
  margin-bottom: 0;
  padding-left: 0;
}
.u-tab__menu li {
  list-style: none;
}
.u-tab__menu>* {
  width: calc(33.333333% - 1rem);
  margin-right: 1rem;
}
.u-tab__item {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #2b2a27;
  text-align: center;
  text-decoration: none;
  padding: 0.6em 0.5em;
  border: 1px solid #2b2a27;
  border-bottom: 0;
  box-sizing: border-box;
  background: #f3efe6;
  cursor: pointer;
  transition-property: background;
  transition-duration: 0.3s;
}
.u-tab__item[aria-expanded="true"] {
  color: #fff;
  padding: 1.0em 0.5em;
  background: #2b2a27;
}
.u-tab__item:not([aria-expanded="true"]):hover {
  color: #2b2a27;
  background: #e8dc6a;
}
.u-tab__item:focus-visible {
  outline: 3px solid #e8dc6a;
  outline-offset: -3px;
}
.u-tab__item-main {
  flex-grow: 1;
  font-size: 16px;
  text-align: center;
}
.u-tab__body {
  display: none;
  font-size: 16px;
  border: 1px solid #2b2a27;
  padding: 40px;
}
.u-tab .u-block {
  display: block;
}
.u-tab .u-none {
  display: none;
}
.u-tab + .u-tab {
  margin-top: 1.5rem;
}
@media screen and (max-width: 736px) {
  .u-tab__body {
    padding: 20px;
  }
}
@media (prefers-reduced-motion: reduce) {
  .u-tab__item { transition: none; }
}

jQuery

roleとaria-expandedを使ってタブが切り替わるようにしています。
keyCodeの指定もしています。

$(function(){
  if($('.u-tab').length){
    // URL の ?tab=1 などで、はじめに開くタブを決める(0 から数える)
    var splitNum = location.search.substr(1).split(/&/);
    var list = new Object();
    for(var i=0;i<splitNum.length;i++){
      var localsplit = splitNum[i].split(/=/);
      list[localsplit[0]] = localsplit[1];
    }
    // 動きを減らす設定のときは、ふわっと出さない
    var speed = window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 400;
    $('.u-tab').each(function (){
      var tabMenu = $(this).find('[role="tab"]');
      var tabPanel = $(this).find('[role="tabpanel"]');
      if(list["tab"] && list["tab"].search(/^[-]?[0-9]+$/) == 0 && tabMenu[list["tab"]] ){
        tab( $(tabMenu[list["tab"]]) );
      }else if( !tabMenu.is('[aria-expanded="true"]') ){
        tab( $(tabMenu[0]) );
      }
      tabMenu.on('click', function() {
        tab($(this));
        return false;
      });
      tabMenu.on("keydown", function(e) {
        if (e.keyCode == 13){
          $(this).trigger("click");
        }else if (e.keyCode == 39){
          $(this).parent().next().children().focus().trigger("click");
        }else if (e.keyCode == 37){
          $(this).parent().prev().children().focus().trigger("click");
        }
      });
      function tab(obj){
        if(obj.attr('aria-expanded') == 'false'){
          tabMenu.attr('aria-expanded', 'false');
          obj.attr('aria-expanded', 'true');
          tabPanel.hide().attr('aria-expanded', 'false');
          tabPanel.eq(obj.parent().index()).attr('aria-expanded', 'true').fadeIn(speed);
        }
      }
    });
  }
});

タブを2個置いてみる(プラグインなし)

同じソースをコピペするだけオッケーですね。
あー、簡単簡単。

コードを見る(HTML・CSS・jQuery)

HTML

<div class="u-tab">
  <ul class="u-tab__menu" role="tablist">
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="true"><span class="u-tab__item-main">タブ1</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ2</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ3</span></a>
    </li>
  </ul>
  <div class="u-tab__body u-block" role="tabpanel" aria-expanded="true">タブ1のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ2のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ3のこと</div>
</div>
<div class="u-tab">
  <ul class="u-tab__menu" role="tablist">
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="true"><span class="u-tab__item-main">タブ1</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ2</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ3</span></a>
    </li>
  </ul>
  <div class="u-tab__body u-block" role="tabpanel" aria-expanded="true">タブ1のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ2のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ3のこと</div>
</div>

CSS

.u-tab__menu {
  display: flex;
  align-items: flex-end;
  margin-right: -1rem;
  margin-bottom: 0;
  padding-left: 0;
}
.u-tab__menu li {
  list-style: none;
}
.u-tab__menu>* {
  width: calc(33.333333% - 1rem);
  margin-right: 1rem;
}
.u-tab__item {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #2b2a27;
  text-align: center;
  text-decoration: none;
  padding: 0.6em 0.5em;
  border: 1px solid #2b2a27;
  border-bottom: 0;
  box-sizing: border-box;
  background: #f3efe6;
  cursor: pointer;
  transition-property: background;
  transition-duration: 0.3s;
}
.u-tab__item[aria-expanded="true"] {
  color: #fff;
  padding: 1.0em 0.5em;
  background: #2b2a27;
}
.u-tab__item:not([aria-expanded="true"]):hover {
  color: #2b2a27;
  background: #e8dc6a;
}
.u-tab__item:focus-visible {
  outline: 3px solid #e8dc6a;
  outline-offset: -3px;
}
.u-tab__item-main {
  flex-grow: 1;
  font-size: 16px;
  text-align: center;
}
.u-tab__body {
  display: none;
  font-size: 16px;
  border: 1px solid #2b2a27;
  padding: 40px;
}
.u-tab .u-block {
  display: block;
}
.u-tab .u-none {
  display: none;
}
.u-tab + .u-tab {
  margin-top: 1.5rem;
}
@media screen and (max-width: 736px) {
  .u-tab__body {
    padding: 20px;
  }
}
@media (prefers-reduced-motion: reduce) {
  .u-tab__item { transition: none; }
}

jQuery

roleとaria-expandedを使ってタブが切り替わるようにしています。
keyCodeの指定もしています。

$(function(){
  if($('.u-tab').length){
    // URL の ?tab=1 などで、はじめに開くタブを決める(0 から数える)
    var splitNum = location.search.substr(1).split(/&/);
    var list = new Object();
    for(var i=0;i<splitNum.length;i++){
      var localsplit = splitNum[i].split(/=/);
      list[localsplit[0]] = localsplit[1];
    }
    // 動きを減らす設定のときは、ふわっと出さない
    var speed = window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 400;
    $('.u-tab').each(function (){
      var tabMenu = $(this).find('[role="tab"]');
      var tabPanel = $(this).find('[role="tabpanel"]');
      if(list["tab"] && list["tab"].search(/^[-]?[0-9]+$/) == 0 && tabMenu[list["tab"]] ){
        tab( $(tabMenu[list["tab"]]) );
      }else if( !tabMenu.is('[aria-expanded="true"]') ){
        tab( $(tabMenu[0]) );
      }
      tabMenu.on('click', function() {
        tab($(this));
        return false;
      });
      tabMenu.on("keydown", function(e) {
        if (e.keyCode == 13){
          $(this).trigger("click");
        }else if (e.keyCode == 39){
          $(this).parent().next().children().focus().trigger("click");
        }else if (e.keyCode == 37){
          $(this).parent().prev().children().focus().trigger("click");
        }
      });
      function tab(obj){
        if(obj.attr('aria-expanded') == 'false'){
          tabMenu.attr('aria-expanded', 'false');
          obj.attr('aria-expanded', 'true');
          tabPanel.hide().attr('aria-expanded', 'false');
          tabPanel.eq(obj.parent().index()).attr('aria-expanded', 'true').fadeIn(speed);
        }
      }
    });
  }
});

タブを3個置いてみる(プラグインなし)

同じソースをコピペするだけオッケーですね。
あー、なんて楽なんだー。

コードを見る(HTML・CSS・jQuery)

HTML

<div class="u-tab">
  <ul class="u-tab__menu" role="tablist">
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="true"><span class="u-tab__item-main">タブ1</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ2</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ3</span></a>
    </li>
  </ul>
  <div class="u-tab__body u-block" role="tabpanel" aria-expanded="true">タブ1のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ2のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ3のこと</div>
</div>
<div class="u-tab">
  <ul class="u-tab__menu" role="tablist">
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="true"><span class="u-tab__item-main">タブ1</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ2</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ3</span></a>
    </li>
  </ul>
  <div class="u-tab__body u-block" role="tabpanel" aria-expanded="true">タブ1のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ2のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ3のこと</div>
</div>
<div class="u-tab">
  <ul class="u-tab__menu" role="tablist">
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="true"><span class="u-tab__item-main">タブ1</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ2</span></a>
    </li>
    <li>
      <a href="#" class="u-tab__item" role="tab" aria-expanded="false"><span class="u-tab__item-main">タブ3</span></a>
    </li>
  </ul>
  <div class="u-tab__body u-block" role="tabpanel" aria-expanded="true">タブ1のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ2のこと</div>
  <div class="u-tab__body" role="tabpanel" aria-expanded="false">タブ3のこと</div>
</div>

CSS

.u-tab__menu {
  display: flex;
  align-items: flex-end;
  margin-right: -1rem;
  margin-bottom: 0;
  padding-left: 0;
}
.u-tab__menu li {
  list-style: none;
}
.u-tab__menu>* {
  width: calc(33.333333% - 1rem);
  margin-right: 1rem;
}
.u-tab__item {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #2b2a27;
  text-align: center;
  text-decoration: none;
  padding: 0.6em 0.5em;
  border: 1px solid #2b2a27;
  border-bottom: 0;
  box-sizing: border-box;
  background: #f3efe6;
  cursor: pointer;
  transition-property: background;
  transition-duration: 0.3s;
}
.u-tab__item[aria-expanded="true"] {
  color: #fff;
  padding: 1.0em 0.5em;
  background: #2b2a27;
}
.u-tab__item:not([aria-expanded="true"]):hover {
  color: #2b2a27;
  background: #e8dc6a;
}
.u-tab__item:focus-visible {
  outline: 3px solid #e8dc6a;
  outline-offset: -3px;
}
.u-tab__item-main {
  flex-grow: 1;
  font-size: 16px;
  text-align: center;
}
.u-tab__body {
  display: none;
  font-size: 16px;
  border: 1px solid #2b2a27;
  padding: 40px;
}
.u-tab .u-block {
  display: block;
}
.u-tab .u-none {
  display: none;
}
.u-tab + .u-tab {
  margin-top: 1.5rem;
}
@media screen and (max-width: 736px) {
  .u-tab__body {
    padding: 20px;
  }
}
@media (prefers-reduced-motion: reduce) {
  .u-tab__item { transition: none; }
}

jQuery

roleとaria-expandedを使ってタブが切り替わるようにしています。
keyCodeの指定もしています。

$(function(){
  if($('.u-tab').length){
    // URL の ?tab=1 などで、はじめに開くタブを決める(0 から数える)
    var splitNum = location.search.substr(1).split(/&/);
    var list = new Object();
    for(var i=0;i<splitNum.length;i++){
      var localsplit = splitNum[i].split(/=/);
      list[localsplit[0]] = localsplit[1];
    }
    // 動きを減らす設定のときは、ふわっと出さない
    var speed = window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 400;
    $('.u-tab').each(function (){
      var tabMenu = $(this).find('[role="tab"]');
      var tabPanel = $(this).find('[role="tabpanel"]');
      if(list["tab"] && list["tab"].search(/^[-]?[0-9]+$/) == 0 && tabMenu[list["tab"]] ){
        tab( $(tabMenu[list["tab"]]) );
      }else if( !tabMenu.is('[aria-expanded="true"]') ){
        tab( $(tabMenu[0]) );
      }
      tabMenu.on('click', function() {
        tab($(this));
        return false;
      });
      tabMenu.on("keydown", function(e) {
        if (e.keyCode == 13){
          $(this).trigger("click");
        }else if (e.keyCode == 39){
          $(this).parent().next().children().focus().trigger("click");
        }else if (e.keyCode == 37){
          $(this).parent().prev().children().focus().trigger("click");
        }
      });
      function tab(obj){
        if(obj.attr('aria-expanded') == 'false'){
          tabMenu.attr('aria-expanded', 'false');
          obj.attr('aria-expanded', 'true');
          tabPanel.hide().attr('aria-expanded', 'false');
          tabPanel.eq(obj.parent().index()).attr('aria-expanded', 'true').fadeIn(speed);
        }
      }
    });
  }
});

いまの書き方

いまは、jQuery を使わなくても、素の JavaScript で 30 行ほどで書けます。タブは『a』ではなく『button』にすると、Enter・スペースで押せるので、キーの番号(keyCode)を書かなくて済みます。
選んでいるタブは『aria-selected』、パネルの表示・非表示は『hidden』で切りかえます。タブとパネルをむすぶ『aria-controls』『aria-labelledby』の id は、JavaScript で付けているので、同じ HTML をいくつ置いても大丈夫です。

コードを見る(HTML・CSS・JavaScript)

HTML

<div class="tabs">
  <div class="tabs__menu" role="tablist">
    <button type="button" class="tabs__item" role="tab" aria-selected="true">タブ1</button>
    <button type="button" class="tabs__item" role="tab" aria-selected="false">タブ2</button>
    <button type="button" class="tabs__item" role="tab" aria-selected="false">タブ3</button>
  </div>
  <div class="tabs__body" role="tabpanel">タブ1のこと</div>
  <div class="tabs__body" role="tabpanel" hidden>タブ2のこと</div>
  <div class="tabs__body" role="tabpanel" hidden>タブ3のこと</div>
</div>
<div class="tabs">
  <div class="tabs__menu" role="tablist">
    <button type="button" class="tabs__item" role="tab" aria-selected="true">タブ1</button>
    <button type="button" class="tabs__item" role="tab" aria-selected="false">タブ2</button>
    <button type="button" class="tabs__item" role="tab" aria-selected="false">タブ3</button>
  </div>
  <div class="tabs__body" role="tabpanel">タブ1のこと</div>
  <div class="tabs__body" role="tabpanel" hidden>タブ2のこと</div>
  <div class="tabs__body" role="tabpanel" hidden>タブ3のこと</div>
</div>

CSS

.tabs__menu {
  display: flex;
  align-items: flex-end;
  gap: 1rem;
}
.tabs__item {
  flex: 1;
  color: #2b2a27;
  font: inherit;
  font-size: 16px;
  padding: 0.6em 0.5em;
  border: 1px solid #2b2a27;
  border-bottom: 0;
  background: #f3efe6;
  cursor: pointer;
  transition: background 0.3s;
}
.tabs__item[aria-selected="true"] {
  color: #fff;
  padding: 1.0em 0.5em;
  background: #2b2a27;
}
.tabs__item:not([aria-selected="true"]):hover {
  background: #e8dc6a;
}
.tabs__item:focus-visible {
  outline: 3px solid #e8dc6a;
  outline-offset: -3px;
}
.tabs__body {
  font-size: 16px;
  border: 1px solid #2b2a27;
  padding: 40px;
  animation: tabs-fade 0.4s;
}
.tabs + .tabs {
  margin-top: 1.5rem;
}
@keyframes tabs-fade {
  from { opacity: 0; }
}
@media screen and (max-width: 736px) {
  .tabs__body {
    padding: 20px;
  }
}
@media (prefers-reduced-motion: reduce) {
  .tabs__item { transition: none; }
  .tabs__body { animation: none; }
}

JavaScript

document.querySelectorAll('.tabs').forEach(function (box, n) {
  var tabs = box.querySelectorAll('[role="tab"]');
  var panels = box.querySelectorAll('[role="tabpanel"]');

  function show(i) {
    tabs.forEach(function (tab, j) {
      tab.setAttribute('aria-selected', j === i);
      tab.tabIndex = j === i ? 0 : -1; // Tab キーで入るのは、選んでいるタブだけ
      panels[j].hidden = j !== i;
    });
  }

  tabs.forEach(function (tab, i) {
    // タブとパネルを id でむすぶ(読み上げで「タブ1のパネル」とわかる)
    tab.id = 'tabs' + n + '-tab' + i;
    panels[i].id = 'tabs' + n + '-panel' + i;
    tab.setAttribute('aria-controls', panels[i].id);
    panels[i].setAttribute('aria-labelledby', tab.id);

    tab.addEventListener('click', function () {
      show(i);
    });
    // ← → で となりのタブへ(Enter・スペースは button なので、そのまま押せる)
    tab.addEventListener('keydown', function (e) {
      var move = { ArrowRight: 1, ArrowLeft: -1 }[e.key];
      if (!move) return;
      var next = (i + move + tabs.length) % tabs.length;
      show(next);
      tabs[next].focus();
    });
  });

  // URL の ?tab=2 などで、はじめに開くタブを決める(1 から数える)
  var start = new URLSearchParams(location.search).get('tab');
  show(start >= 1 && start <= tabs.length ? start - 1 : 0);
});

どれを使う?

  • jQuery をもう読みこんでいるサイト → 上のコードのまま
  • 新しく作る・jQuery を使っていない → 『button』+『aria-selected』+『hidden』の素の JavaScript
  • タブの名前を読み上げで伝えたい → どちらでも、タブとパネルを『aria-controls』でむすぶ

ふわっと出すのは CSS の『animation』にしたので、動きを減らす設定にしている人には、すぐに切りかわります。URL の『?tab=2』で、はじめに開くタブも決められます(こちらは 1 から数えます)。

メモ

jQueryのことで何かわからないことがあればjQueryの日本語リファレンスサイトがあるので一度チェックしてみるのをおすすめします。

さいごに

デザオ
わー、使いやすいですー
デザコト
外部ページからのリンクIDも可能にしたい場合は、下の記事のほうがいいですねー

ふたりの小言

関連記事

ほかの見本は、みほんちょうに。

デザコトauthor

あ、いいな、と思うWebデザインを紹介しています。デザインの参考に。やさしいデザインが多いです。Webデザインギャラリー『デザインのこと - Web design gallery』を運営しています。