Skip to content

Instantly share code, notes, and snippets.

@nabrown
Created September 12, 2018 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nabrown/9508341262fa0947e8f8fbe33ff93667 to your computer and use it in GitHub Desktop.
Save nabrown/9508341262fa0947e8f8fbe33ff93667 to your computer and use it in GitHub Desktop.
Using a mutation observer to watch for attribute changes
(function() {
// Select the node to observe
var targetNode = document.querySelector('.sqs-add-to-cart-button');
// The class we'll watch for
var className = 'cart-added';
// If the targetNode exists on our page
if(targetNode){
// Observe attributes, specifically the class attribute
// We don't care about descendant nodes
var config = {
attributes: true,
attributeFilter: ['class'],
subtree: false
};
// When a mutation is observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
// If the classList contains the className we want, go to the cart page
if(mutation.target.classList.contains(className)){
window.location.href = '/cart';
}
}
};
// Create an new observer
var observer = new MutationObserver(callback);
// Start observing
observer.observe(targetNode, config);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment