Adi – 11-24 Jun 10

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/
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
S
ScriptyChris678d ago
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>
A
Adi678d ago
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')
S
ScriptyChris678d ago
show the updated code, please
A
Adi678d ago
Sorry my bad issue got resolved. Silly mistake from my end Closing this thread
S
ScriptyChris678d ago
you may react to helpful answer with ✅ to resolve a thread
A
Adi678d ago
Yes done ✅
UU
Unknown User677d ago