Sugumar Venkatesan
Sugumar Venkatesan

Reputation: 4028

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

Upvotes: 4

Views: 4376

Answers (2)

Kiril
Kiril

Reputation: 2963

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

Upvotes: 6

Lo&#239;c Faure-Lacroix
Lo&#239;c Faure-Lacroix

Reputation: 13600

Your code is being executed before the DOM is actually being loaded... For that reason, you're passing a null/undefined value to the observe method.

Wrap your code inside:

$( document ).ready(function() {
....
})

Also calling disconnect will prevent it from receiving any event. So you shouldn't call disconnect right after calling observe. And you're missing a parameter to the observe call.

Check here for a working exemple:

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#Example_usage

Upvotes: 5

Related Questions