mdibound
mdibound

Reputation: 101

MutationObserver watching for style change only firing once

I have the following div:

<div id="new-address-modal" style="display:none;"> </div>

With a MutationObserver that is being triggered on attribute change (thus I need it to trigger whenever the style attribute changes

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
    console.log('style changed!');
  });    
});

var target = document.getElementById('new-address-modal');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });

But this is only getting triggered once. What should I be doing in order for this to trigger whenever style is changed, after an initial trigger?

Thank you!

Upvotes: 2

Views: 4261

Answers (1)

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

What you have works, you are just not changing the style of the attribute so it never get triggered.

In this example, all I am doing is changing the background color every second. Mutation observers do not trigger on the initial creation of the element, so if that is what you are expecting, you will need to create a function and trigger it when the element gets loaded.

If you are modifying the value from one thing to the same thing this will also never trigger the event.

For example:

<!-- HTML -->
<div style="background: red"></div>

// JavaScript
target.style.background = 'red'

As you can see it is red, and we are trying to set it to red. the mutation will not trigger because nothing changed.

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutationRecord) {
    console.log('style changed!');
  });
});

var target = document.getElementById('new-address-modal');
observer.observe(target, {
  attributes: true,
  attributeFilter: ['style']
});

// My only edits:
setInterval(function(){
  target.style.display = Math.floor(Math.random() * 2) == 0 ? 'none' : 'initial'
}, 1000)
<div id="new-address-modal" style="display:none;">Now you see me</div>

In the example you can see that when the value stays the same it never gets triggered.

Upvotes: 2

Related Questions