R
Reactiflux

Adi – 11-24 Jun 10

Adi – 11-24 Jun 10

AAdi6/10/2022
I am loading JS file which is internally generating CSS/HTML content and appending it in body & head tag. Now is it possible to add event listeners for html elements or do I need to create another script tag and wait for previous script to load? Can I have html elements and event listeners both in same JS file? check this https://jsfiddle.net/y19x6re4/
SScriptyChris6/10/2022
you can apply event listeners after that HTML code is parsed to the DOM (a.k.a. loaded) you can also apply event listener to the root of where that HTML is appended and utilize event delegation (so no need wait for HTML to be parsed) https://davidwalsh.name/event-delegate it should be fine to add event listeners after this line
html.innerHTML = htmlString;
html.innerHTML = htmlString;
side question: why do you have init function marked as async? you don't use await there about buttons you want to add event listeners to
// I want to add click events on button1 and button2
if i found "buttons" you are talking about, then they are not buttons, but divs, which is a bad approach to pick
<div id="pushnotify-button1">
Later
</div>
<div id="pushnotify-button2">
Allow
</div>
<div id="pushnotify-button1">
Later
</div>
<div id="pushnotify-button2">
Allow
</div>
these should be
<button id="pushnotify-button1">
Later
</button>
<button id="pushnotify-button2">
Allow
</button>
<button id="pushnotify-button1">
Later
</button>
<button id="pushnotify-button2">
Allow
</button>
AAdi6/10/2022
I tried adding events after that string but in my case DOM is not getting loaded but JS runs before that. Also init is async because I have some other calculations done in that same function like some promises are used inside it I have already tried what you suggested: getting this message error TypeError: Cannot read properties of null (reading 'addEventListener')
SScriptyChris6/10/2022
show the updated code, please
AAdi6/10/2022
Sorry my bad issue got resolved. Silly mistake from my end Closing this thread
SScriptyChris6/10/2022
you may react to helpful answer with ✅ to resolve a thread
AAdi6/10/2022
Yes done ✅
UUUnknown User6/11/2022
Message Not Public
Sign In & Join Server To View

Looking for more? Join the community!

R
Reactiflux

Adi – 11-24 Jun 10

Join Server