Created
September 12, 2018 13:35
-
-
Save nabrown/9508341262fa0947e8f8fbe33ff93667 to your computer and use it in GitHub Desktop.
Using a mutation observer to watch for attribute changes
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
(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