Skip to content

Instantly share code, notes, and snippets.

@greghunt
Last active April 1, 2018 04:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greghunt/66c0cb2baae5cce49dc30ee551517471 to your computer and use it in GitHub Desktop.
Save greghunt/66c0cb2baae5cce49dc30ee551517471 to your computer and use it in GitHub Desktop.
Toggle Class with jQuery
/*
* <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);
});
});
@greghunt
Copy link
Author

greghunt commented Mar 10, 2018

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.

<button data-toggle-class="#targetDiv:some-class">Toggle this Class on the Element</button>

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