/ Tabs

A simple tabs with css

A simple tabs with css

simple tabs

A simple tabs with css.

css/less

.tab-list a {
  display: inline-block;
  padding: 5px 10px;
  margin-right: 5px;

  border: 1px black solid;
  border-bottom-width: 0;
  text-decoration: none;

  &.tab-active {
    background-color: white;
  }
}

magic-tab {
  display: none;
  
  border: 1px black solid;
  padding: 10px;
  
  margin-top: -1px;
  
  &.tab-active {
    display: block;
  }
}

html

<magic-tabs>
  <magic-tab title="Tab one">
    This is the first tab
  </magic-tab>
  <magic-tab title="Tab two">
    This is the second tab
  </magic-tab>
  <magic-tab title="Tab three">
    This is the final tab
  </magic-tab>
</magic-tabs>

js

var tabsProto = Object.create(HTMLElement.prototype);

tabsProto.createdCallback = function () {
  this.tabList = document.createElement('div');
  this.tabList.className = 'tab-list';
  
  this.insertBefore(this.tabList, this.firstChild);
  
  this.addEventListener('click', function (e) {
    if (e.target.tagName === 'A') {
      e.preventDefault();
      
      var tabs = this.tabList.querySelectorAll('a');
      tabs = Array.prototype.slice.call(tabs);
      this.switchTo(tabs.indexOf(e.target));
    }
  });
  
  var activeTab = this.querySelectorAll('.tab-active');
  
  if (activeTab.length === 0) {
    this.querySelector('magic-tab').classList.add('tab-active');
  }
};

tabsProto.switchTo = function (index) {
  this.querySelector('magic-tab.tab-active')
    .classList.remove('tab-active');
  
  this.querySelector('.tab-list .tab-active')
    .classList.remove('tab-active');
  
  this.querySelectorAll('magic-tab')[index]
    .classList.add('tab-active');
  
  this.querySelectorAll('.tab-list a')[index]
    .classList.add('tab-active');
};


document.registerElement('magic-tabs', {
  prototype: tabsProto
});


var tabProto = Object.create(HTMLElement.prototype);

tabProto.createdCallback = function () {
  var tabItem = document.createElement('a');
  tabItem.innerText = this.title;
  tabItem.href = '#';
  this.parentElement.tabList.appendChild(tabItem);
  
  if (this.classList.contains('tab-active')) {
    tabItem.className = 'tab-active';
  }
};

document.registerElement('magic-tab', {
  prototype: tabProto
});

Author

Callum Macrae

Demo

See the Pen jqlgf by Callum Macrae (@callumacrae) on CodePen.

CodeTea

A Nice collection of often useful examples done in HTML JavaScript CSS.

Read More