Skip to content

Instantly share code, notes, and snippets.

@peeke
Last active November 20, 2016 15:09
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 peeke/e17919bc4171b4bd29a371fcd465b67b to your computer and use it in GitHub Desktop.
Save peeke/e17919bc4171b4bd29a371fcd465b67b to your computer and use it in GitHub Desktop.
Function to listen for attribute changes. Useful for preventing inconsistency between your internal module state and the DOM. (IE11+)
const attributeObserver = (element, attr, cb) => {
const mutObserver = new MutationObserver(mutations => {
mutations.forEach(mut => {
mut.attributeName === attr && cb(element.getAttribute(attr));
});
});
mutObserver.observe(element, {
attributes: true,
attributeFilter: [ attr ]
});
return mutObserver;
};
const handleAttrChangeFn = attrValue => console.log(attrValue);
const ariaHiddenObserver = attributeObserver(document.getElementById('foo'), 'aria-hidden', handleAttrChangeFn);
ariaHiddenObserver.disconnect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment