Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: mutationobserver is not alerting message

I am trying to detect the CSS property changes in an element. I searched online and found MutationObserver javascript API. but in my test script it is not working as expected( it's not alerting the property name and property value).

var foo = document.getElementById("hideit");

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    alert('mutation.type = ' + mutation.type);

  });

});
observer.observe(foo);
observer.disconnect();

$(function() {
  $("#clickhere").on("click", function() {
    $("#hideit").slideToggle('fase');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<body>
  <div id="clickhere">click to toggel</div>
  <div id="hideit" style="display:none;">this is the content of the hide/show toggle</div>

</body>

and it shows a javascript error

TypeError: Argument 1 of MutationObserver.observe is not an object.

Thanks is advance

like image 980
Sugumar Venkatesan Avatar asked Dec 18 '22 18:12

Sugumar Venkatesan


1 Answers

There're 2 problems in your code:

  1. usage of observer.observe is incorrect. It should take 2 params: Node and MutationObserverInit. See the correct API here.
  2. Do not call observer.disconnect(); immediately after observe. Disconnect stops observing.

Working example

like image 148
Kiril Avatar answered Jan 10 '23 05:01

Kiril