ukaric
ukaric

Reputation: 428

MutationObserver and EventListeners

I have this highly specific problem that I can not seem to solve, i need to listen to the DOM change events and I have used Mutation Observer API and I can register addition of div to the DOM but I need to be able to react to clicks on that div and persist data that I get back across navigation for that I resorted to localStorage but I can not seem to trigger observe method when user clicks the link that has been dynamically added.

For better clarification here is what I want to achieve.

  1. Notification is sent and MutationObserver registeter it gets triggered via observe
  2. User clicks on newly added div it expands navigation
  3. Get the notification message, parse it push it to array then store it in localStorage
  4. On next click user is taken to new page where I also need to pickup some data and append it to localStorage

So far I can react to new DOM additions. And I can filter additions of what I need.

Here is the code

function watchForOrder() {
  var mutationObserver = new MutationObserver(function(mutation) {
    mutation.forEach(function(mutation) {
      console.log(mutation);
      //Possible place to create object to store information that I need.
    });
  });
  mutationObserver.observe(document.body, {
    // attributes: true,
    // characterData: true,
    childList: true,
    subtree: true
  });

I also can not disconnect observer because I need it to listen for new additions all the time so my concern is that it may impact performance severely.

tl;dr How can I combine MutationRecord tap into that and set up regular event listener or is that even good idea ?

Upvotes: 1

Views: 4037

Answers (1)

Arnav Choudhury
Arnav Choudhury

Reputation: 41

I was facing a similar issue although my use-case was much easier. I just wanted to attach an onclick event listener to every element as the user scrolls down the news feed. One solution is to simply use "onclick" attribute on the HTML element itself and using "this" you could do what you want.

Another solution is to register an event listener inside the mutation observer. Every time the mutation observer runs (when elements are added/removed) the event listener will get attached to ALL the child elements. This is super clean and then within the event listener you could just call a function that has the logic for making what you want work for 1 element.

Upvotes: 2

Related Questions