Ask Your Question
2

How can I utilize a Mutation observer to add an onClick Event function to a Button that appears after the page has finished loading?

asked 2023-05-25 23:13:33 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-25 23:35:02 +0000

lalupa gravatar image

To utilize a Mutation Observer to add an onClick event function to a button that appears after the page has finished loading, you can follow these steps:

  1. Create a new Mutation Observer object and specify the target element that you want to observe for changes.
const target = document.querySelector('#target-element');
const observer = new MutationObserver(onMutation);
observer.observe(target, { childList: true });
  1. Define a function that will be executed whenever a mutation occurs on the observed element. In this function, you can check if the button element has been added to the DOM and add the event listener to it.
function onMutation(mutationsList, observer) {
  for (let mutation of mutationsList) {
    if (mutation.type === 'childList') {
      const addedNodes = [...mutation.addedNodes];
      const button = addedNodes.find(node => node.nodeName === 'BUTTON');

      if (button) {
        button.addEventListener('click', onClick);
      }
    }
  }
}
  1. Define the onClick event listener function that will be executed when the button is clicked.
function onClick(event) {
  console.log('Button clicked!');
}

Note: Replace '#target-element' in step 1 with the selector of the parent element that contains the button element you want to observe.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-25 23:13:33 +0000

Seen: 8 times

Last updated: May 25 '23