2

My div looks something like this:

<div tabindex="0" role="button" id="profile-pic" style="background-image: "Some url";"></div>

The background image will be updated based on some criteria. I want to set listener to the style property and listen to background image change. Is it possible?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
abhishek maharajpet
  • 482
  • 1
  • 4
  • 18
  • Read about [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver). – 31piy Apr 09 '19 at 10:34
  • Note that the style attribute change (that MutationObserver will be able to observe) doesn't necessarily means the actual background-image change. If the property is set to an invalid value, or if some CSS rules took predescedence (e.g with `!important` keyword), then MutationObserver will report false positives. In the same way, if a CSS rule is applied and takes predescedence over the style attribute's rule, then the MutationObserver will miss it. – Kaiido Apr 10 '19 at 08:37

2 Answers2

7

You can use MutationObserver

Then code example:

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

var target = document.getElementById('myId');

observer.observe(target, { 
  attributes: true, 
  attributeFilter: ['style'] 
});

Note: this only works with inline styles(any changing of styles), not when the style changes as a consequence of class change or @media change This is a answer https://stackoverflow.com/a/20683311/3344953

Yaroslav Trach
  • 1,833
  • 2
  • 12
  • 18
Ryan Nghiem
  • 2,417
  • 2
  • 18
  • 28
2

It's possible with MutationObserver, but it's a somewhat odd thing to do:

console.log('Script start');
const div = document.querySelector('div');

const o = new MutationObserver(() => {
  console.log('style changed');
});
o.observe(div, { attributes: true, attributeFilter: ["style"] });

setTimeout(() => {
  div.style.backgroundImage = 'url(https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1)';
}, 500);
<div tabindex="0" role="button" id="profile-pic" style="background-image: 'Some url';">xx</div>

It would make a lot more sense for the function that makes the style change to call other functions that need to know that the change happened.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320