Problem with addeventlistener

Could someone explain why this is making the function run before any button has been pressed? Should this not wait until deletePostBtn has been clicked before running deletepost()?
deletePostBtn.addEventListener("click", deletePost())
deletePostBtn.addEventListener("click", deletePost())
6 Replies
b1mind
b1mind•3y ago
because you are calling the function when passing it in. So it is running when it creates the listener.. deletePostBtn.addEventListener("click", () => {deletePost()}) You could wrap it in a function/arrow func
Jon
JonOP•3y ago
Thanks man, i think i tried that but it didnt work. Turns out i was just having issues with button it self. Im making it in js so i was trying to select it before it was created 🙃
b1mind
b1mind•3y ago
use defer in your <script> import😄 anytime the JS needs your DOM, or ran after page load.
b1mind
b1mind•3y ago
if you don't need to pass params you could do it without the calling it too. (I typically just always wrap it so I can access the event.) deletePostBtn.addEventListener("click", deletePost)
Jon
JonOP•3y ago
Ohhh thanks! I'll read up on that
Want results from more Discord servers?
Add your server