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β€’2y 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
Jonβ€’2y 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β€’2y ago
use defer in your <script> importπŸ˜„ anytime the JS needs your DOM, or ran after page load.
b1mind
b1mindβ€’2y 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
Jonβ€’2y ago
Ohhh thanks! I'll read up on that