0

I have a div that is dynamically changed, and I need to trigger a javascript function when a property of the div is changed.

Inputbox has a property named onChange. Is there something similar for divs? I need the function to trigger when values like background-color, height, top, etc. are changed.

<div id="hello" onChange="Changed()">Espinete</div>

function Changed(){alert('The div was changed');}

  • 1
    Note that the best answer in the duplicate is regarding the use of a Mutation Observer to achieve what you need: https://stackoverflow.com/a/42805882/519413. The answers suggesting DOMSubtreeModified are outdated. – Rory McCrossan Mar 27 '19 at 13:46

2 Answers2

0

Edit: The solution below is deprecated, sorry.

Try using the DOMNodeInserted and DOMNodeRemoved events.

$('#hello').on('DOMNodeInserted DOMNodeRemoved', function() {
    alert('The div was changed');
});
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
Elizabeth
  • 499
  • 2
  • 10
  • 1
    Note that the events you've used in your edit are still deprecated. In fact, all mutation events are: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events – Rory McCrossan Mar 27 '19 at 13:48
0

You can use MutationObserver. Here is a demo

let div = document.querySelector('div');

setTimeout(() => div.style.backgroundColor= "red",2000);

var data = { attributes: true, childList: true, subtree: true };

let x = new MutationObserver((list) => {
  console.log(list[0].target.style.backgroundColor)
})
x.observe(div,data)
<div>Something</div>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73