MutationObserver and Event Usage
I want to explain it through an example. Say you have your own company and you’re working with e-commerce companies. Your customer says to you “Can you provide user’s last added product for another consultant company. We need this information” and you said “Yes, we can do this”
Of course, you can find a professional solution to this problem. I’ll make this with MutationObserver and Event. MutationObserver is using detect DOM changes. For example, you have an element. You can detect any changes in this element. Adding a new child element, changing element content, adding a new attribute, etc. I used it for my card page element. It’s imitating a basic cart page. I’ll add a child div to here as a product.
I added a new child element in this code.
I used setTimeout to wait for 4000 milliseconds. Because we want to detect DOM changes. It’ll trigger after 4000 milliseconds. You can review MutationObserver sample codes from here:
I wrote createAndTriggerEvent function for creating a new Event and triggering it. When our data is ready we’re triggering it.
Finally, I’m listening to our custom event. When it’s triggering we’re catching data.
You can get all JavaScript codes from here: