Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for MutationObserver
Hasan TEZCAN
Hasan TEZCAN

Posted on

     

MutationObserver

What is the mutation observer?

MutationObserver is a JavaScript API that allows developers to listen for changes to specific elements or nodes in the DOM (Document Object Model). It provides a way to observe and respond to changes that occur within the DOM structure.

The MutationObserver works by registering a callback function to observe a specific target element or node in the DOM. When a change occurs, such as a node being added or removed, the callback function is called with a list of MutationRecord objects that describe the changes that have occurred.

The MutationObserver API provides a powerful tool for building responsive web applications that need to react to changes in the DOM. It can be used to implement a wide range of features, such as lazy-loading content, auto-updating UI elements, and real-time data synchronization.


Let me explainmutation observer through an example.

Our aim is to add an animation when the category's section height changes. We need to listen that operation

beforeafter
beforeafter

In order to do this we need a reference of the category section.

importReact,{useRef}from'react';import{CategoryItems}from'./category-items/category-items';import{CategoryTitles}from'./category-titles/category-titles';import'./categories.scss';constCategories=()=>{constcategoriesRef=useRef<HTMLDivElement>(null);return(<divclassName="categories"ref={categoriesRef}><CategoryTitles/><CategoryItems/></div>);};export{Categories};
Enter fullscreen modeExit fullscreen mode

After preparing thecategoriesRef, we can create themutationObserver structure.

First of all, we need to create mutationObserver

constmutationObserver=newMutationObserver(async()=>{console.log('mutationObserver operation');});
Enter fullscreen modeExit fullscreen mode

This is our mutationObserver instance we will call this instance fromuseEffect

useEffect(()=>{if(categoriesRef.current){mutationObserver.observe(categoriesRef.current,{childList:true,subtree:true,});return()=>{mutationObserver.disconnect();};}},[]);
Enter fullscreen modeExit fullscreen mode
  • We definedmutationObserver.observe withcategoriesRef.current which listens to theparameters such aschildList andsubtree, also you can checkthis out for more parameters.

  • And also we define themutationObserver.disconnect() oncomponentWillUnmount hook for delete listen operation when component closed.

Henceforward when the height change atcategoriesRef we will see the console log.

console.log('mutationObserver operation');
Enter fullscreen modeExit fullscreen mode

Then we will add the animation handler code piece and define a CSS transition tocategoriesRef

constmutationObserver=newMutationObserver(async()=>{constcategoryTitles=document.getElementById('categoryTitles')asHTMLDivElement|null;constcategoryItems=document.getElementById('categoryItems')asHTMLDivElement|null;if(categoriesRef.current&&categoryTitles&&categoryItems){if(categoryTitles.clientHeight>categoryItems.clientHeight){categoriesRef.current.style.height=`${categoryTitles.clientHeight}px`;}else{categoriesRef.current.style.height=`${categoryItems.clientHeight}px`;}}});
Enter fullscreen modeExit fullscreen mode
.categories{transition:height200msease;}
Enter fullscreen modeExit fullscreen mode

after

voilà 🎉

Source

Top comments(6)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
sergeyleschev profile image
Sergey Leschev
Team Lead (Swift, TypeScript, SQL). LeetCode Ranking #Dev TOP 200 Global. Google Engineering Level: L7+

Great post! In addition to its many uses, it's worth noting that the MutationObserver API can also be useful for automating tasks that require DOM manipulation. With its ability to detect changes in real-time, devs can use this API to trigger certain actions upon specific mutation events, such as updating elements or triggering animations. This makes it a valuable tool for improving both the functionality and user experience of web applications.

CollapseExpand
 
yagmurmutluer9 profile image
Yağmur
computer science student, loves to write
  • Location
    Mugla, Turkey
  • Joined

awesome, thank you

CollapseExpand
 
hasantezcan profile image
Hasan TEZCAN
Hi, my name is Hasan Tezcan, and I'm a software developer based in Denizli, Turkey. I specialize in building web applications using a variety of programming languages, including Ruby, Java, and JavaSc
  • Location
    Turkey
  • Education
    Pamukkale University
  • Work
    Trendyol
  • Joined

🌸

CollapseExpand
 
fruntend profile image
fruntend
Highly qualified front-end industry research organization
  • Education
    university
  • Work
    CEO
  • Joined

Сongratulations 🥳! Your article hit the top posts for the week -dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

CollapseExpand
 
reacthunter0324 profile image
React Hunter
  • Joined

It's great

CollapseExpand
 
hasantezcan profile image
Hasan TEZCAN
Hi, my name is Hasan Tezcan, and I'm a software developer based in Denizli, Turkey. I specialize in building web applications using a variety of programming languages, including Ruby, Java, and JavaSc
  • Location
    Turkey
  • Education
    Pamukkale University
  • Work
    Trendyol
  • Joined

🙏

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi, my name is Hasan Tezcan, and I'm a software developer based in Denizli, Turkey. I specialize in building web applications using a variety of programming languages, including Ruby, Java, and JavaSc
  • Location
    Turkey
  • Education
    Pamukkale University
  • Work
    Trendyol
  • Joined

More fromHasan TEZCAN

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp