Skip to content

Instantly share code, notes, and snippets.

@tarekziade
Created March 21, 2018 10:05
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 tarekziade/d542c0904641da1a96c4bf636e07fdbf to your computer and use it in GitHub Desktop.
Save tarekziade/d542c0904641da1a96c4bf636e07fdbf to your computer and use it in GitHub Desktop.
Demonstrates how to detect when a button gets enabled
/* Like for the IntersectionObserver, we're using here the
* Mutation observer to detect when an element attribute is changed
* by some Javascript on the page.
*
* use case: a button is enabled
*/
function watchMutation(selector, condition) {
var target = document.querySelector(selector);
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (condition(target, mutation)) {
console.log("timer!"); // <-- this is where we sendAsync the date.now()
observer.disconnect();
}
});
});
var config = {attributes: true, childList: true, characterData: true}
observer.observe(target, config);
}
/*
* Example of usage: detect when #button is enabled
*
* caveat: probably introduces a slight overhead that can vary between firefox and google chrome
* but measuring the overhead should also stay consistent unless the MutationObserver implementation
* itself has evolved.
*/
window.addEventListener("load", function(event) {
function canTriggerTimer(target) {
return !target.disabled;
}
watchMutation("#button", canTriggerTimer);
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment