My problem is that I want to track attribute change on an element using custom event, I have been reading on mozilla developers, I still don't get it.
So, how does custom events work? and How to use it to track attribute change/variable change(of a class).
Standard event listeners respond to many things, but element attribute changes are not one of them. A MutationObserver is really the only way to build something like this yourself, short of a resource-heavy setInterval
faux-listener.
var target = document.querySelector('button');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.attributeName + ' atrribute was changed.');
});
});
observer.observe(target, {
attributes: true
});
Here is a JSFiddle where a button click changes an element's color, which is picked up by the MutationObserver.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.