admin管理员组

文章数量:1290950

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=".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>

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./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

Share Improve this question edited May 9, 2018 at 11:20 Code Guru 15.6k30 gold badges143 silver badges210 bronze badges asked Mar 23, 2016 at 8:22 Sugumar VenkatesanSugumar Venkatesan 4,03810 gold badges48 silver badges82 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

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/en-US/docs/Web/API/MutationObserver#Example_usage

本文标签: mutation observersJavascript mutationobserver is not alerting messageStack Overflow