Last active
September 30, 2017 07:48
-
-
Save shelldandy/e4a9065359f7147e9b736211507a8e84 to your computer and use it in GitHub Desktop.
Tabs using vanilla JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Most likely works IE10+ so hell yeah (?)