Dynamic change in the mutation observer is not causing the callback to trigger

I have created a nested structure with two <div> elements. I am monitoring changes in the width of the inner <div>, which is set to width:auto;. Despite adjusting the width of the parent <div>, the mutation observer callback doesn't seem to trigger as expected when the target <div>'s width changes. What could be causing this issue?

// Targeting the element with changing display value
var blocker = document.querySelector('#blocker');
// Trigger to modify the display value of blocker
var trigger = document.querySelector('#trigger');
// Mutation observer to track attribute changes on blocker
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    // Was it the style attribute that changed? (Consider checking for other attribute changes too)
    if (mutation.attributeName === 'style') {
      alert(window.getComputedStyle(blocker).getPropertyValue('width'));
    }
  });
});

// Attaching the mutation observer to blocker, and focusing only on attribute value changes
observer.observe(blocker, {
  attributes: true
});

// Modifying the style attribute of blocker upon trigger
trigger.addEventListener('click', function() {
  $('#d').css('width', '300px');
}, false);
#d {
  width: 200px;
}
#blocker {
  width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="d">
  <div id="blocker" style="display:none">Stop!</div>
</div>
<div id="trigger">Show blocking element</div>

View on JSFiddle

Answer №1

Observing the #blocker div, a child of the #d div, reveals that when clicked, the parent attributes (#d) are altered. However, the MutationObserver is limited to observing either the element itself or the element and its subtree (see MDN). As a result, the callback is not triggered because only the attributes of another DOM element are being modified.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my token to not save after registering a user?

I am currently facing an issue when submitting a registration form. While the user is successfully created, the token is not stored in localStorage, which prevents me from being redirected immediately to the app and forces me to log in again. Here is my R ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

The background-size property fails to function properly on mobile devices

It's really puzzling why this issue is happening, perhaps it's due to my fatigue. The problem lies in the fact that the "background-size" property isn't functioning on my mobile devices; however, it works perfectly when I try to simulate it ...

Receiving a commitment from an Angular Resource

When working with $resource in Angular for CRUD operations, I'm encountering some confusion regarding the usage of different resource methods. From what I've observed, the "regular" methods like save() and get() appear to execute synchronously. ...

Exploring the Wonder of MVC with Ajax Calls Handling Multiple Parameters

I've been struggling to send 2 parameters from the View to the controller using an ajax call. Everything was working fine when I had only one parameter, but as soon as I added another, the function stopped working. Below is the Javascript code with a ...

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

Problem with input field borders in Firefox when displayed within table cells

Demo When clicking on any cell in the table within the JSFiddle using Firefox, you may notice that the bottom and right borders are hidden. Is there a clever solution to overcome this issue? I have experimented with a few approaches but none of them work ...

Implementing a feature to automatically set the datepicker value to the selected date upon page initialization

I am working with a datepicker element, identified by id="from_dt", and a button with id="fromToDate". When a date is selected from the datepicker and the button is clicked, the page will load. At that point, I want to transfer the selected date to a textb ...

Video Autoplay within an image carousel - A seamless integration

I need assistance embedding a YouTube video as the fourth item in a slideshow on my website, www.serenitygardenrooms.com. The slideshow should play the first three images and then autoplay the video before moving on to the next image. However, the code sni ...

Is it possible for JavaScript within an <iframe> to access the parent DOM when

Is it possible for javascript in an iframe from a different domain to modify the parent's DOM? I need my iframed script to add new html elements to the parent page - any suggestions? Edit: One potential solution is using "Fragment ID Messaging" to co ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

Is there a way to track when the Angular DTOptionsBuilder ajax call is complete and trigger a callback function?

Working with angular datatables, I have the following code: beforeSend:

success callback causes the table on the page not to populate with the data. How can I implement a callback that triggers once the ajax is done without interfering with the nor ...

Is there a way to access an object within another object without the need to use a function

Having trouble accessing an object? Let's solve this mystery together. I'm trying to access 'ctx', but base.ctx keeps returning null (is there a closure involved?). window.base = function () { var c = null, ctx = null; ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

Place a <script> tag within the Vue template

I am currently developing an integration with a payment service. The payment service has provided me with a form that includes a script tag. I would like to insert this form, including the script tag, into my component template. However, Vue does not allo ...

The app.html for the skygear/react-chat-demo is malfunctioning

I followed the instructions provided in the Skygear manual at https://docs.skygear.io/guides/advanced/server/ The skygear-server-darwin-amd64 started successfully. Then, I attempted to run the react-chat-demo project from https://github.com/skygear-de ...

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...

Using the position property of relative on a DIV element causes a gap to appear between the DIV and the next

Two div elements are placed consecutively. When I move the first div using position: relative and top: -60px, it creates a gap between them. Take a look at this example here: https://codepen.io/dusannis/pen/oNgBpoK If you notice, there is a noticeable ga ...

To avoid the sudden appearance of a div on the screen, React is programmed to wait for the

Struggling with preventing a flashing div in React where the error message renders first, followed by props, and finally the props render. The EventsView component includes the following code: view.js var view; if (_.size(this.props.events) !== 0) { vie ...

The font size calculation is larger than the CSS definition on the Asus Nexus 7 device

Running the website on an Asus Nexus 7 (developed in jQueryMobile), I set the font size in CSS to be 14px. However, while debugging using Chrome on my PC, I noticed that the computed size is actually 22px. Here's a snippet of the HTML code: <div ...