Skip to content

Instantly share code, notes, and snippets.

@IgorGavrilenko
Last active August 3, 2022 11:20
Show Gist options
  • Save IgorGavrilenko/a9fb9fad6464a7f25bdfad68c35ce1c6 to your computer and use it in GitHub Desktop.
Save IgorGavrilenko/a9fb9fad6464a7f25bdfad68c35ce1c6 to your computer and use it in GitHub Desktop.
MutationObserver
// mutation
var observeObject = function () {
var _class = {
init: function (selector, callback) {
var element = document.querySelector(selector);
try {
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
callback(mutation.target, mutation.attributeName, mutation.oldValue);
});
});
observer.observe(element, {
attributes: true,
subtree: true,
attributeOldValue: true
});
} catch (z) {
element.addEventListener('DOMAttrModified', function (e) {
callback(e.target, e.attrName, e.prevValue);
}, false);
}
}
};
return _class;
}();
$(function () {
observeObject.init('selector-init', function (target, name, oldValue) {
if (target.getAttribute('class') == 'class-init') {
$('selector').addClass('class');
} else {
$('selector').removeClass('class');
}
});
});
/////////////////////////////////////////////////////////////////////
const selector = document.querySelector('.selector');
if(checkbox){
const options = {
attributes: true
}
function callback(mutationList, observer) {
mutationList.forEach(function(mutation) {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
if($('.selector').hasClass('search-class')) {
$('.selector').addClass('add-class');
}
else {
$('.selector').removeClass('add-class');
}
}
})
}
const observer = new MutationObserver(callback)
observer.observe(selector, options)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment