Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

luca-dev's avatar

[Question] How do I intercept a button click from a button that was generated from a string?

Hey everyone, I'm stuck on a pretty interesting and in my eyes difficult problem. I'm calling an endpoint through the fetchook (the fetch hook wuill be called once the user has entered an ID into the searchbar) and then receives a payload. The payload has multiple objects but two of them are of special interested right now ('raw-logs' and 'https-logs'). These two objects will be manipulated in such a way that the content of it looks like this: raw-logs: ' Click Me! ' (the same goes for the https-logs but with a different ID). Now here's my problem: Since the button will be generated from a string I can't use any Vue or Nuxt directives because it'll be rendered by the DOM instead of Vues' / Nuxt's rendering engine. How can I intercept the button click? I want to intercept this and based on the ID of the button want to execute the same function but choose a different payload for the modal. Can anyone help me?

0 likes
3 replies
LaryAI's avatar
Level 58

To intercept a button click from a button that was generated from a string, you can use event delegation. You can add a click event listener to the parent element of the button and check if the target element is the button that was clicked. If it is, you can execute the desired function based on the ID of the button.

Here's an example code snippet:

// Assuming the parent element has an ID of "parent-element"
const parentElement = document.getElementById('parent-element');

parentElement.addEventListener('click', (event) => {
  if (event.target.tagName === 'BUTTON') {
    const buttonId = event.target.id;
    // Execute desired function based on buttonId
  }
});

In this example, we're adding a click event listener to the parent element and checking if the target element is a button. If it is, we're getting the ID of the button and executing the desired function based on the ID.

luca-dev's avatar

@LaryAI why do I need to use event delegation? Couldn't I simply listen for the button itself instead of using an event listener for the parent element?

SDCODE's avatar
// Assume 'payload' is the object received from the endpoint
const rawLogsButton = document.createElement('button');
rawLogsButton.innerText = payload['raw-logs'];
rawLogsButton.addEventListener('click', () => {
  // Execute function for 'raw-logs' payload
});

const httpsLogsButton = document.createElement('button');
httpsLogsButton.innerText = payload['https-logs'];
httpsLogsButton.addEventListener('click', () => {
  // Execute function for 'https-logs' payload
});

// Add the buttons to the DOM
document.getElementById('button-container').appendChild(rawLogsButton);
document.getElementById('button-container').appendChild(httpsLogsButton);

Please or to participate in this conversation.