No technology has divided the programming community more than JavsScript, mainly because it’s the been de-facto standard for web pages since around 2012, or possibly earlier. Developers either love it or hate it. I’m in the camp that says let’s do without it. But that’s for another post.
ur doing it rong
Basically, early on my projects began like this. You might have had similar experiences.
A LT;DR Explanation of Why This Happens
When the page loads in a browser, the browser engine loads the page and parses the content linearly. After, just saying that, you can see the problem: the browser engine can’t see the button yet!
In fact, if you look in the console, you’ll see the error message displayed.
We can get around this in 2 ways. The first way is simply to move the script portion to below the body.
This is fairly standard, especially if you want to include external scripts and scripts from a CDN, since the browser engine can load the direct content of the page before waiting eons for a request from an external CDN.
we hit the
<script> tag, so we can add a listener to the DOM.
Notice we need to use the
DomContentLoaded event or else the code will not
of the page is loaded (essentially doing the same thing as adding the script
to the bottom–except that just the code inside the event handler is
executed). Because the DOM content is loaded, that means the button exists, and
the button can now use a click event listener.
The Point: Rocket vs. Roadie
Most langauges you can think of as a rocket ship. You hit the EXECUTE button and things start happening. Once the program executes, everything that goes on is already there, and you’re already aware of what the input is and output should be.
Even when writing plug-ins this is true. Plug-in API usually tells you the expected input and output.
The band is the main event. The roadie is there, waiting for the next order order form the band. However, the roadie has to wait for the band’s instruction. Doesn’t matter if the roadie is the fast and efficient. Starting a stage tear-down during the climactic song set will ruin the performance and the roadie will be fired.
But, once the band asks the roadie to do something (moving equipment, testing the batteries on mics, handing out water), he knows exactly what to do and can do it without the band’s instructions.