Created
March 21, 2018 10:05
-
-
Save tarekziade/d542c0904641da1a96c4bf636e07fdbf to your computer and use it in GitHub Desktop.
Demonstrates how to detect when a button gets enabled
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
/* 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