Skip to content

Instantly share code, notes, and snippets.

@hellobrian
Created June 23, 2016 21:58
Show Gist options
  • Save hellobrian/e5762979ca832170475dd2698c0e4bc0 to your computer and use it in GitHub Desktop.
Save hellobrian/e5762979ca832170475dd2698c0e4bc0 to your computer and use it in GitHub Desktop.
Material Tabs
<ul>
<li><a data-pos="0" class="active" href="#tab1">tab 1</a></li>
<li><a data-pos="1" href="#tab2">tab 2</a></li>
<li><a data-pos="2" href="#tab3">tab 3</a></li>
<li><a data-pos="3" href="#tab4">tab 4</a></li>
</ul>
<div class="slider"></div>
const tabs = document.querySelectorAll('a');
const numberOfTabs = tabs.length;
const tabsContainer = document.querySelector('ul');
const slider = document.querySelector('.slider');
slider.style.width = `calc(100%/${numberOfTabs})`;
tabsContainer.addEventListener('click', function(event) {
Array.prototype.forEach.call(tabs, function(tab) {
const isActive = tab.classList.contains('active');
const isSelf = event.target;
tab.classList.remove('active');
if (isSelf && !isActive) {
isSelf.classList.add('active');
slider.style.transform = `translateX(${isSelf.dataset.pos * 100}%)`;
}
});
});
* {
box-sizing: border-box;
}
body {
padding: 0;
margin: 0;
}
ul {
background-color: orange;
display: flex;
list-style-type: none;
padding: 0;
margin: 0;
}
li {
text-align: center;
flex: 1;
}
a {
background-color: salmon;
display: inline-block;
text-decoration: none;
font-family: sans-serif;
width: 100%;
color: teal;
padding: 1rem 0;
}
.slider {
background-color: blue;
height: 5px;
display: block;
transition: transform 200ms;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment