Part 2 in a 5 part series. Part 1 is here.
At this point you should have two files, a server.js and an index.html sitting in the same directory.
For this part, we’ll just be working with index.html, so you could simply point your web browser to C:/your/file/path/index.html and it will work fine, but why not get in the habit of starting your node server? You’ll see changes to index.html reflected when you refresh the page either way.
Use the “Inspect element” to find out how Chrome interpreted our 4 lines of HTML:
Our file only contained <h1> tags and the <script> tags. <html>,<head>, <body>, and this mysterious “#shadow-root” were all added by the web browser before rendering. On top of that, in the bottom-center there’s styling added on to the <h1> element: all of this display: block; font-size: 2em; -webkit-margin-before etc. is added by Chrome to make our barebones HTML code look presentable. So like I said, you can leave a lot out and modern web browsers will figure out how to render your page anyway.
Here, ‘onclick’ listens to that ‘myButton’ element, ready to react to a click at any moment. This is different than, for instance, programming an Arduino, where we’d have to check whether a button is pressed continuously in an infinite loop. Instead, we can write a function that executes only in response to the web browser noticing that the user clicked their mouse while hovering over the button element. This is “Event driven programming.” (You actually can do event driven programming with Arduino, if you know about hardware interrupts.)
While chaining those identifiers and functions all together on one line works OK, programming like that quickly gets hard to read. It’s much better practice to break it into pieces.
- Create a variable called button and assign it the myButton element.
- Create a function called speak, which calls on the alert function to say hi.
- Attach the ‘onclick’ event listener to the button variable and assign the function named ‘speak’ as its action.
By the way, you don’t have to have a button element to be able to click on it. I like the look of h1 better, so I’ll just click on those. I’ll change the color style of the h1 elements with each click as well. (side effect: button elements default to a block-inline style whereas header elements default to block style)
In the next section, we’ll plug a lamp into an Arduino:
Note: “Handling Events” recommends using ‘addEventListener’ instead of ‘onclick’, which is a better way to do it. Onclick events are limited to one-per-element, whereas you can ‘addEventListeners’ as much as you want. But for a simple example I like the syntax of .onclick better.