MutationObserver - Detect change in div childs - javascript

I need to call an action when there are changes in the DOM in the children of a parent DIV. I saw that there is this method (MutationObserver) but I tried to add it on WORDPRESS and I can't print on the console even when there are changes. I wanted to do it through class because the id is dynamic from the parent div.
I am trying this code on a page.
// select the target
alert('This is Test 1');
var target = document.querySelector('#mmp-map-2b40f571');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
alert('This is a test 2');
});
});
// configuration of the observer
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);
/* mais tarde vocĂȘ pode parar de observar
observer.disconnect();*/
The action only runs when I open the page and whenever there are changes in the levels below this div it does not enter the action. In the image link you can see the JavaScript debbug in the inspect
https://www.screencast.com/t/9UWSLh4D4r
I appreciate help :)

Related

How to stop a MutationObserver observing a single target?

To move this old mutation event jQuery code
$('#container .class').on('DOMNodeInserted.mynamespace', 'input[type="number"]', function (e) {
...
$(this).closest('#container .class').off('DOMNodeInserted.mynamespace');
});
to MutationObserver, I have to add the observer to multiple elements at once:
var observer = new MutationObserver(function (mutations, observer) {
...
});
var config = {
subtree: true,
childList: true
};
$("#container .class").each(function () {
observer.observe(this, config);
});
But how can I similarly remove the observer from a single element at a time (after the first time the event/observer runs successfully) to retain the behaviour of the pre-MutationObserver version?

Javascript event that is triggered when browser loads new inline (ajax) content?

Is there a Javascript event that is triggered when browser loads new inline (ajax) content? I would like to catch new content as it happens inside my browser extension. Thanks to all
window.onload = function() {
var observer = new MutationObserver(function(mutations) {
alert("hello");
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe($('#contentArea'), config);
}
Using the DOM Mutation Observer will most likely be what you want.
// Since you are using JQuery, use the document.ready event handler
// which fires as soon as the DOM is fully parsed, which is before
// the load event fires.
$(function() {
var observer = new MutationObserver(function(mutations) {
alert("DOM has been mutated!");
});
var config = {
attributes: true,
childList: true,
characterData: true
};
// You must pass a DOM node to observe, not a JQuery object
// So here, I'm adding [0] to extract the first Node from
// the JQuery wrapped set of nodes.
observer.observe($('#contentArea')[0], config);
// Then, the DOM has to be mutated in some way:
$("#contentArea").html("<p>test</p>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contentArea"></div>

Implementing MutationObserver in place of DOMSubtreeModified

I have a select[multiple] which I have given a class custom-multiselect on my page for which I am catching the DOMSubtreeModified event as follows:
HTML:
<select class="custom-multiselect"></select>
JQuery:
$('.custom-multiselect').each(function (i, select) {
var sel = this;
adjustHeight(sel); //Custom function
//Binding DOMSubtreeModified to catch if the select list gets modified by the user
$(sel).on('DOMSubtreeModified', function () {
adjustHeight(sel);
});
//For Internet Explorer
$(sel).on('propertychange', function () {
adjustHeight(sel);
});
});
This approach works flawlessly. I want to convert the DOMSubtreeModified function into MutationObserver since DOMSubtreeModified is depreciated.
So I did something like this:
var observer = new MutationObserver(function (mutation) {
mutation.forEach(function (m) {
if (m.type == 'subtree') {
adjustHeight(this);//Can I use m.target here?
}
});
});
observer.observe(document.querySelector('select.custom-multiselect'), {
subtree: true
});
But I end up getting error
TypeError: The expression cannot be converted to return the specified type.
How can I convert my DOMSubtreeModified event to be observed by the MutationObserver?
Put the code in place of the old DOM event and use your sel variable as the observation target;
Use childList option in MutationObserver because subtree doesn't specify what to look for;
There's no need to check the mutations since you subscribe only to one type.
$('.custom-multiselect').each(function() {
var sel = this;
adjustHeight(sel);
new MutationObserver(function() {
adjustHeight(sel);
}).observe(sel, {childList: true, subtree: true});
});
Or, if you like .bind for some reason:
new MutationObserver(adjustHeight.bind(null, sel))
.observe(sel, {childList: true, subtree: true});

Listening to DOM events (specific attributes)

I need to get data when a specific attribute is added .
I have read this post : Is there a JavaScript/jQuery DOM change listener?
var observer = new MutationObserver(function (mutations, observer) {
// fired when a mutation occurs
$.each(mutations, function(index, mutation) {
var post = $(mutation.target).find('div[class^="ContentWrapper"]');
});
});
observer.observe(document, {
subtree: true,
attributes: true
});
There is a problem with this approach because there are to many events and the extension is very slow,is there an option to filter the mutations,by specific attribute?
Use attributeFilter in the MutationObserverInit options. Set it to an array of attributes that you want to listen for like so:
var attributeSpecificObserver=new MutationObserver(function_you_want_observing);
attributeSpecificObserver.observe( element_you_want_to_observe, {
attributeFilter: ['id', 'class', 'style', 'etc'],
} );
Source: Mozilla Developer Network (MDN).

Watch attribute changes with Jquery

I need to fire an event when a div's attribute changes. I came across this plugin http://meetselva.github.io/attrchange/ and it seems to do the trick. The only problem is that it's firing the event multiple times. For example, if I do:
$("#sgPluginBox").attrchange({
callback: function(evnt) {
if(evnt.attributeName == "style") {
alert('test');
}
}
});
it will show eight alert boxes. I have no idea why it's doing that. I need it to only show one alert box when the style attribute is changed. Any suggestions?
EDIT:
Not the most elegant solution but it looks like using $.one(alert('test')) did the trick.
Try using MutationObserver
$(document).ready(function() {
var target = $("#test").get(0);
// create an observer instance
var observer = new MutationObserver(function(mutations) {
if (mutations.length) {
alert(mutations[0].attributeName + " changed")
target.innerHTML = target.style.fontSize;
// disconnect `observer`
this.disconnect()
}
});
// configuration of the observer:
var config = {
attributes: true
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
$("#test").attr("style", "font-size:36px");
setTimeout(function() {
$("#test").attr("style", "font-size:52px")
.html($("#test").css("fontSize"))
},
1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="test" style="font-size:20px;">abc</div>

Categories