Last active
July 6, 2018 15:26
-
-
Save whmii/7e0590a3aa3d380e7177d6cdca627d27 to your computer and use it in GitHub Desktop.
Toggle Class written in ES
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
class Toggle { | |
constructor(element) { | |
this.trigger = element; | |
this.triggerText = this.trigger.textContent; | |
this.triggerAlternativeText = this.trigger.dataset.toggleTriggerAlternativeText; | |
this.triggerActiveClass = this.trigger.dataset.toggleTriggerActiveClass; | |
this.targetIDs = JSON.parse(this.trigger.dataset.toggle); | |
this.targets = []; | |
this.targets = this.targetIDs.map(id => document.getElementById(id)); | |
this._bindEvents(); | |
} | |
_bindEvents() { | |
this.trigger.addEventListener('click', (event) => this._toggle(event)); | |
} | |
_toggle(event) { | |
event.preventDefault(); | |
if (this.triggerAlternativeText) { | |
this._updateTextContent(); | |
} | |
this.trigger.classList.toggle(this.triggerActiveClass); | |
this._toggleTargets(); | |
} | |
_toggleTargets() { | |
this.targets.forEach((element) => { | |
let targetActiveClass = element.dataset.toggleTargetActiveClass; | |
element.classList.toggle(targetActiveClass); | |
}); | |
} | |
_updateTextContent() { | |
[ this.trigger.textContent, | |
this.trigger.dataset.toggleTriggerActiveTextContent, | |
] = [ | |
this.triggerAlternativeText, | |
this.triggerText ], | |
[ this.triggerText, | |
this.triggerAlternativeText, | |
] = [ | |
this.trigger.textContent, | |
this.trigger.dataset.toggleTriggerActiveTextContent, | |
]; | |
} | |
} | |
Array.from(document.querySelectorAll('[data-toggle]')).forEach((element) => { | |
new Toggle(element); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment