Detecting DOM change using Mutation observer- 11 mins
- Do it yourself - Step 1
- Do it yourself - Step 2
- Do it yourself - Step 3
- Do it yourself - Step 4
- Do it yourself - Step 5
Detecting and get notified when dom changes is a common scenario for developers. Previously it could be done using Mutation events. But it had a huge performance degradation and stability issue (see here). That’s why it has announced as deprecated and recommended to avoid. In future release of the browsers, this might be removed from their engines too.
On 2011 a new proposal for MUTATION OBSERVER had announced. It resolved the performance issue at the same time keeping the same functionality.
Today we’ll implement a basic mutation observer and will discuss about its structure.
What will we do?
- Step 1: First we will create a basic boilerplate with a list of text..
- Step 2: Then we will create a js snippet with basic data..
- Step 3: Initially, we’ll change the text to its translated one..
- Step 4: Then we will create a mutation observer and start it to observe changing data..
- Step 5: Show a list of log output and disconnect observer when done.. (disconnect is important)
Do it yourself - Step 1
Let’s try it out.
Initially create a html boilerplate. Create a css file style.css and a js file mutation.js on same directory.
Now update html markup within body. Here div with the id changeMe contains actual data we will mutate. Next div with id log will show the log data whenever data changes on upper div.
Next add some styling code. Add following css on style.css
So our basic boilerplate is ready. Next we will start with mutation.js file.
Do it yourself - Step 2
Add an array of corresponding spanish translation for each list text.
Set two variable targetNode as text selector and logNode for log destination.
Let’s add some variable which we will use later.
Do it yourself - Step 3
The function changeText will pick the text from list using targetNode selector and current index. Index is initialized with 0. So index will be incremented by 1 when call next and upon calling the same function whenever it become eqal to loop (wait… what is it???!!!) we call translationOp to stop.
First if condition states that when it is the second item from list (remember list index start from 0. So 1 means second list item) we change it’s id to ‘newId’
If you follow along you’ve already recognized that a setInterval method is calling the function and translationOp variable is keeping the setInterval as a reference. and if it equals to loop (again !!!) it will stop.
Until now if it looks confusing, don’t stop. Continue the reading. I’m sure you will catch up within a minute.
Here are the initialization function init and the mysterious loop which is actually a normal variable has the length of our list of text. We’re creating a setInterval method which is calling our changeText each 3s until stopped.
I hope this section is clear. If not run the code. Revise whole code top to bottom carefully. For reference here’s the final version on codepen
Do it yourself - Step 4
So far so good!
Now we will create the mutation observer.
First add observerTarget selector and a variable called observer on top of the script.
Now implement observeChange function. The whole code is already documented. So I am giving a short brief on that.-
- mutationNotifier is a function which will be used as a callback function for mutation observer.
- a new instance of mutation observer is declared using new MutationObserver and assigned to observer variable. It takes a callback function as the its parameter.
- We’ve added configuration config for mutation server. We can set boolean value true or false for each of them based on our target.
- Then we call our mutation observer instance using observer method and as parameter give the target node to watch (observerTarget declared before) and defined configuration config.
- When the observer need stopping, we will call stopObserver function. This will disconnect the observer.
Let’s initialize the observeChange from main function init.
Do it yourself - Step 5
Now observer is watching. But how do we know it’s working?
Let’s show some log output to watch if it’s working or not.
Create a addLog function which will add our log item on logNode (previously declared) target.
Now add a log after calling mutation observer.
Also, add a log within stopObserver function when observer disconnect.
The only place left is within mutation observer callback function mutationNotifier. Each mutation object has a set of value which is return after mutation/change happens. Detail on each key has been given below.
Within switch method, I am checking for type of mutation and based on that adding to log.
That’s it. We’ve implemented a basic mutation observer and observe the text change. Please check the resources section for complete code link and other few resources I recommend.
Recommended reading on MDN.
DOM standard spec.