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
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
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 button2if i found "buttons" you are talking about, then they are not buttons, but divs, which is a bad approach to pick these should be
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')
show the updated code, please
Sorry my bad issue got resolved. Silly mistake from my end
Closing this thread
you may react to helpful answer with ✅ to resolve a thread
Yes done
✅
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