This isn't really a question, more like an informative post that will hopefully spare other newbies hours of frustration and despair. I googled this, but couldn't find anything on this particular issue. Not on W3Schools, not on mozilla.org, not on javascript.info, nothing. Hopefully others will find this thread when they google this problem. I'm sorry if this is an inappropriate use of this forum.
tl;dr: When assigning a function to an event listener or handler, don't use parentheses, unless you're using HTML.
As an example, here's the first part of a document:
<!DOCTYPE html>
<html>
<head>
<script>
function test() {
alert("Test");
}
</script>
<body>
<button id="go">Go!</button>
Now the second part. First version:
<script>
document.getElementById("go").onclick = test();
</script>
</body>
</html>
Second version:
<script>
document.getElementById("go").onclick = test;
</script>
</body>
</html>
In the first version, the parameter brackets are used when the function is assigned: test(). In the second version, the brackets aren't used. The first is incorrect, the second is correct.
In the first version, test() is erroneously executed immediately when the page loads, before the DOM is loaded. In the second version, everything works as it should. In the first version, due to the curly brackets, the JS engine believes it should run the function, instead of assigning it to onclick. Apparently, the creators of JS believed there is no point in using a parameter of a function in the case of an assignment, e.g. onclick = test(some_var).
In contrast, the following is correct:
<button id="go" onclick="test()">Go!</button>
This works as it should. When you leave out the parentheses...
<button id="go" onclick="test">Go!</button>
...it does not work, because here, onclick is not JS code. It's an HTML attribute that executes JS code.
Again, sorry if this little tutorial is inappropriate here. I'm new to JavaScript, and every time I google something about it, Stack Overflow threads show up at the top of the results. This forum has been invaluable to me, and I'm sure it has been to many other trainee programmers around the world. Thanks to everyone who contributes here!