0

Lets say you have a create button that dynamically creates a element and a button element named play. The play button has an eventlistener("click") that has a variable named timer that equals set interval which runs a function named start timer that displays a time elapsed within the innerHTML of the p that was created.

QUESTION: Since there can be multiple timer buttons created, how can you bind the play button clicked with the p element that it was created with?

aplua
  • 132
  • 14
madQuestions
  • 109
  • 1
  • 7
  • @Barmar Please reopen this question as what is being asked is not answered by the Event Delegation question you marked as a dup. The question is actually asking about how to target a dynamically created element from an event handler. – Scott Marcus Jun 13 '22 at 22:21
  • Event delegation is the way you do that. – Barmar Jun 13 '22 at 22:24
  • Or you can just add the event listener to the new element after you create it. `element = document.createElement('button'); element.addEventListener(...)` – Barmar Jun 13 '22 at 22:25
  • Hello @Barmar, as Scott stated, please reopen this ticket as this doesn't answer my question. The subject states Vanilla Javascript. You closed the ticket and added a Jquery discussion that if it were vanilla javascript wouldn't help me with my problem. Thanks. – madQuestions Jun 13 '22 at 23:05
  • I didn't link to a jQuery discussion, I linked to a question that's about vanilla JS. – Barmar Jun 13 '22 at 23:07
  • Your follow up comment to Scott is just declaring the variable and adding the event listener. The question in bold questions binding the multiple p elements and event listeners that were created dynamically. – madQuestions Jun 13 '22 at 23:07
  • Please post a [mre] showing how you're creating the elements but the event listener doesn't work. – Barmar Jun 13 '22 at 23:07
  • You use DOM navigation to find related elements, e.g. `event.currentTarget.nextElementSibling` if the p is the next element. – Barmar Jun 13 '22 at 23:09
  • Sure @ Barmar. Please see the code in the following link. https://stackoverflow.com/questions/72606545/javascript-event-listener-e – madQuestions Jun 13 '22 at 23:12

0 Answers0