Mutation observer in vanilla JS

·

3 min read

Introduction to Mutation Observer in JavaScript

Mutation Observer is a powerful API in JavaScript that simplifies the process of observing mutations in the DOM tree and notifying developers about the changes. In the past, developers had to rely on various event listeners to monitor specific changes in the DOM. With Mutation Observer, this process becomes more streamlined and efficient.

Traditional Event Listeners for DOM Mutations

Before Mutation Observer, developers used event listeners such as below to track changes in the DOM. These event listeners were specific to certain types of mutations and required attaching separate listeners for different types of changes.

  • DOMAttrModified
  • DOMAttributeNameChanged

  • DOMCharacterDataModified

  • DOMElementNameChanged

  • DOMNodeInserted

  • DOMNodeInsertedIntoDocument

  • DOMNodeRemoved

  • DOMNodeRemovedFromDocument

  • DOMSubtreeModified

Example: Using Mutation Observer

Let's explore how Mutation Observer simplifies the process of monitoring DOM mutations with an example. Consider a scenario where we want to observe changes to the style attribute of a text element and notify the user whenever such changes occur.

<html>
<head>
  <!-- Head content -->
</head>

<body>
    <div style="font-size: x-large;font-weight: 600;" class="text-element"> 
        Click me to change the text color. 
    </div>
    <script src="script.js"></script>
</body>
</html>

In the provided HTML code snippet, we have a div element with the class text-element, which represents the text element we want to observe for style attribute changes.

const textElement = document.querySelector('.text-element');

function handleClick() {
    const random = Math.floor(Math.random() * 10000);
    textElement.style.color = `#${random}`;
}

const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
            alert('Hey user, there is some change in the style of the text element.');
        }
     });
}); 

observer.observe(textElement, { attributes: true });

In the JavaScript code, we first select the text element using querySelector. Then, we define a function handleClick to change the text element's color to a random value when clicked.

Next, we create a Mutation Observer instance with a callback function that receives mutations as its argument. Within the callback, we iterate through the mutations and check if the mutation is related to the style attribute. If it is, we display an alert to notify the user about the style change.

Finally, we call the observe method on the observer instance to start observing the text element for attribute changes, specifically for changes in the style attribute.

When observers are no longer needed, developers can disconnect them using the .disconnect() method, ensuring efficient resource management and optimal performance.

Additional Use Cases of Mutation Observer:

  1. Form Validation with Real-Time Feedback: By setting the subtree option to true, you can observe changes within the DOM subtree of a form element. This allows for real-time form validation by monitoring input elements and their attributes. For instance, detecting changes to input values, checking for valid email formats, or ensuring required fields are filled. If any validation criteria are not met, appropriate error messages can be displayed to the user instantly, providing a seamless and responsive form validation experience.

  2. Detecting DOM Manipulations: Mutation Observer can be utilized to detect and respond to DOM manipulations performed by scripts or external libraries. Setting the childList option to true enables monitoring changes to the child nodes of a specific element. This includes additions or removals of child elements, as well as changes in their attributes or content. By observing these mutations, developers can ensure data integrity, track changes made by external scripts, and maintain the expected structure and behavior of the DOM.

These are just a few examples of how Mutation Observer can be applied to various scenarios in web development, offering a flexible and powerful tool for DOM observation and manipulation. By understanding and leveraging its capabilities, developers can create more dynamic, responsive, and robust web applications.

Conclusion

Mutation Observer offers a comprehensive solution for observing and reacting to changes in the DOM, enabling developers to build more interactive, responsive, and robust web applications. By leveraging Mutation Observer for various use cases, developers can enhance user experience, streamline development workflows, and ensure compatibility across different browsers and environments.