Adi
Adi3y ago

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.
7 Replies
ScriptyChris
ScriptyChris3y 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>
Adi
Adi3y 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')
ScriptyChris
ScriptyChris3y ago
show the updated code, please
Adi
Adi3y ago
Sorry my bad issue got resolved. Silly mistake from my end Closing this thread
ScriptyChris
ScriptyChris3y ago
you may react to helpful answer with ✅ to resolve a thread
Adi
Adi3y ago
Yes done ✅
reactibot
reactibot3y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/984780166154813472