4.5 - JS + HTML
Connecting two technologies to create interactive pages!
When you "visit" a page in a browser, it loads as much of the code as possible before displaying it. This includes any <script> tags that it finds.
If the <script> tag is at the beginning, it will load (and run) that code first.
If it's at the end of the document, it will be the last thing it loads.
The <script> tag can be used to type code directly into the HTML document:
That is called inline code and is considered the old way of doing it.
This line will read (and run) the code - so it's best to put your code in functions that are called when you want.
Let's test it!
Go to your HTML Playground and add console.log("Hello World!"); to your script.js file. Then run your code.
Ok, that's boring - let's print the title of our HTML page: console.log(document.title);
How does that work?
To manipulate an element, first it must have a unique id in the HTML. Some examples:
document.getElementById("Some id") // This will return a handle of the first element found with the matching ID. This is why unique identifiers are crucial.
There are many aspects of an element that you can change; too many to teach but you can look them up! The main ones are innerHTML, innerText, textContent, hidden, and style. The rest you can learn later.
Ok, cool, but how do we make elements react like when clicked, etc?
There are many events you can listen for - look them up!
Live Demo (sorry - gotta be in class to see it!)