Skip to content

Instantly share code, notes, and snippets.

@shelldandy
Last active September 30, 2017 07:48
Show Gist options
  • Save shelldandy/e4a9065359f7147e9b736211507a8e84 to your computer and use it in GitHub Desktop.
Save shelldandy/e4a9065359f7147e9b736211507a8e84 to your computer and use it in GitHub Desktop.
Tabs using vanilla JS
/**
* Make a document.querySelectorAll loopable
* @author Todd Motto
* @tutorial https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack
* @param {NodeList} elements
* @param {Function} callback function that takes element and index
* @param {this} scope what this refers to
*/
const loopQuery = (elements, callback, scope) => {
for (let i = 0; i < elements.length; i++) {
callback.call(scope, i, elements[i])
}
}
export default loopQuery
import loopQuery from './loopQuery'
const ACTIVECLASS = 'js-tab-active'
const tabLinks = document.querySelectorAll('.tabs-header a')
const tabContents = document.querySelectorAll('.tab-contents > div')
/**
* Remove the active class from the tabs
*/
const removeClass = () => {
loopQuery(tabLinks, (i, link) => {
link.classList.remove(ACTIVECLASS)
})
loopQuery(tabContents, (i, div) => {
div.classList.remove(ACTIVECLASS)
})
}
// Attach handlers to each link
loopQuery(tabLinks, (i, link) => {
link.addEventListener('click', event => {
event.preventDefault()
removeClass()
const target = document.getElementById(link.href.split('#')[1])
// Add the active class to our active link and contents
target.classList.add(ACTIVECLASS)
link.classList.add(ACTIVECLASS)
})
})
section.event-tabs
.tabs-header
a.js-tab-active(href='#a') Tab A
a.tab(href='#b') Tab B
.tab-contents
#a.js-tab-active
h1 Tab A
#b
h1 Tab B
@shelldandy
Copy link
Author

Most likely works IE10+ so hell yeah (?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment