Last active
April 1, 2018 04:51
-
-
Save greghunt/66c0cb2baae5cce49dc30ee551517471 to your computer and use it in GitHub Desktop.
Toggle Class with jQuery
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
/* | |
* <button data-toggle-class="#targetDiv:some-class">Toggle this Class on the Element</button> | |
*/ | |
$("[data-toggle-class]").on('click', function(e){ | |
e.preventDefault(); | |
const config = $(this).data('toggle-class').split(':'); | |
const $target = $(config[0]); | |
const className = config[1]; | |
$target.toggleClass(className); | |
}); | |
/* | |
* Vanilla equivalent | |
*/ | |
document.querySelectorAll('[data-toggle-class]').forEach((element) => { | |
element.addEventListener('click', (event) => { | |
event.preventDefault(); | |
const [target, className] = element.getAttribute('data-toggle-class').split(':'); | |
document.querySelector(target).classList.toggle(className); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful jQuery function I use in almost every project. Keep your animations and toggling behaviour in your CSS, and you can reuse this trigger for most of your behavioural needs.