0

Read many questions regarding this here. Searched across MDN Docs & W3Schools etc. But I have not been able to fix this issue and this is overwhelming me. It seems like very normal and easy thing but isn't working out for me. Probably I have some issues here. The thing is I have 3 different files:
1.index.html contains only a button and script tag.
2.qn1.js contains some functions. It is a module & imports an object from the third file.
3.personAccounts.js contains an export object.

The error:

When I loaded the file in the browser, the index file is as
<script src="day8/level3/qn1.js" type="module"></script>
<button id="btn" > Click here! </button>
and the module contains:
document.getElementById("btn").addEventListener("click", comm());
So, the comm() function is executed automatically for the first time and is never executed when click on the button

As per THIS ANSWER I tried to make sure that HTML is loaded before Script is executed:

 window.load = function(){
    document.getElementById("btn").addEventListener("click", comm());
 }

But here, the function isn't executed even a single time. I even tried DOMContentLoaded but nothing seems to work. Thanks for looking into it.

  • 2
    First thing I'm noticing is that you are calling `comm()` immediately as you are adding the event listener, rather than when the event is fired. I think you may want `document.getElementById("btn").addEventListener("click", comm);`, passing the function reference, rather than calling it. – mykaf Mar 10 '23 at 22:21
  • 1
    Also, it's `window.onload`, not `window.load`. – Unmitigated Mar 10 '23 at 22:22
  • 1
    thanks guys!! referencing the function and changing the event to `onload` really did solved the problem. :) @mykaf and @Unmitigated –  Mar 10 '23 at 22:28

1 Answers1

0

Thanks guys for helping with the errors that I was making in this context:

First thing I'm noticing is that you are calling comm() immediately as you are adding the event listener, rather than when the event is fired. I think you may want document.getElementById("btn").addEventListener("click", comm);, passing the function reference, rather than calling it. By Mykaf

Also, it's window.onload, not window.load By Unmitigated

window.onload = function(){
document.getElementById("btn").addEventListener("click", comm);
 }