Skip to content

Instantly share code, notes, and snippets.

@chancecorbeil
Created November 16, 2022 02:54
Show Gist options
  • Save chancecorbeil/905dd2247c2ef3ca4298c45ad3671e4d to your computer and use it in GitHub Desktop.
Save chancecorbeil/905dd2247c2ef3ca4298c45ad3671e4d to your computer and use it in GitHub Desktop.
<script>
// * Event trigger on class change
// Watch an element to see if a specific class is added
// If so, trigger event
// This function can be used on multiple targets
function onClassChange(element, callback) {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (
mutation.type === 'attributes' &&
mutation.attributeName === 'class'
) {
callback(mutation.target);
}
});
});
observer.observe(element, { attributes: true });
return observer.disconnect;
}
var ChangeMe = document.querySelector('.ChangeMe');
var ChangeMe2 = document.querySelector('.ChangeMe2');
// Watch element to see if active
var itemToWatch = document.querySelector('.WatchMe');
onClassChange(itemToWatch, (node) => {
node.classList.contains('active')
? ChangeMe.classList.add('active')
: ChangeMe.classList.remove('active');
});
// Watch 2nd element
var itemToWatch2 = document.querySelector('.WatchMe2');
onClassChange(itemToWatch2, (node) => {
node.classList.contains('active')
? ChangeMe2.classList.add('active')
: ChangeMe2.classList.remove('active');
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment