Last active
June 2, 2020 20:23
-
-
Save karen-white/55628264e50f60f4a82c847ba7de9f4f to your computer and use it in GitHub Desktop.
Use Mutation Observer to listen for the Billing step of checkout
This file contains 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
<script> | |
(function(win) { | |
'use strict'; | |
var listeners = [], | |
doc = win.document, | |
MutationObserver = win.MutationObserver || win.WebKitMutationObserver, | |
observer; | |
function ready(selector, fn) { | |
// Store the selector and callback to be monitored | |
listeners.push({ | |
selector: selector, | |
fn: fn | |
}); | |
if (!observer) { | |
// Watch for changes in the document | |
observer = new MutationObserver(check); | |
observer.observe(doc.documentElement, { | |
childList: true, | |
subtree: true | |
}); | |
} | |
// Check if the element is currently in the DOM | |
check(); | |
} | |
function check() { | |
// Check the DOM for elements matching a stored selector | |
for (var i = 0, len = listeners.length, listener, elements; i < len; i++) { | |
listener = listeners[i]; | |
// Query for elements matching the specified selector | |
elements = doc.querySelectorAll(listener.selector); | |
for (var j = 0, jLen = elements.length, element; j < jLen; j++) { | |
element = elements[j]; | |
// Make sure the callback isn't invoked with the | |
// same element more than once | |
if (!element.ready) { | |
element.ready = true; | |
// Invoke the callback with the element | |
listener.fn.call(element, element); | |
} | |
} | |
} | |
} | |
// Expose `ready` | |
win.ready = ready; | |
})(this); | |
ready('#checkoutBillingAddress', function(element) { | |
// do something | |
alert("You're on the billing step!"); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment