0

I need to detect when an element appears and bind an eventListener to it.

There are 2 forms on the webpage, when submitted the first one is deleted and the second one is created dynamically depending on the first form values.

I can only run code onDomReady, I use $(function(){...});

I have tried to check if input[data-name="check3"] exists using setInterval() and when found I bind the eventListener to it.

I also tried to bind the eventListener after the first firm submit using setTimeout().

Both of these solutions "worked", but I wonder if there is a cleaner way to do it.

  • 1
    You don't have control on the function that makes the second form appear? Is this an extension or userscript? – Jean Will Dec 23 '21 at 16:43
  • @JeanWill It's a userscript and yes I don't have control on this function. – displayname Dec 23 '21 at 16:45
  • https://stackoverflow.com/questions/38588741/having-a-reference-to-an-element-how-to-detect-when-it-is-appended-to-the-docum – HDM91 Dec 23 '21 at 16:45

2 Answers2

0

You can use MutationObserver to watch for changes being made to the DOM tree and detect what nodes are added to dom and add event listener to them. there is an example in the documentation that you can use.

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(const mutation of mutationsList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type === 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();
HDM91
  • 1,318
  • 9
  • 16
0

There is an example using MutationObserver.

// element will appear at a random time
setTimeout(() => {
  document.body.insertAdjacentHTML('afterbegin', '<div id="el">#el</div>')
}, Math.floor(Math.random() * 4000) + 1000)


const parentOfELement = document.body

const onMutation = () => {
  if (parentOfELement.querySelector('#el')) {
    observer.disconnect()
    console.log('#el appeared!')
  }
}

const observer = new MutationObserver(onMutation)

observer.observe(parentOfELement, {childList: true})
Jean Will
  • 543
  • 3
  • 11