Setup and Hello World!
Whenever we are writing JS, we can either write the code directly inside the HTML file or we can create a separate JS file that we link into the HTML. To start, we are going to be writing the JS directly inside the HTML file. We are going to use a basic HTML file titled
index.html. We will work directly inside a
<script> tag and open the .html file inside a browser. Saving the file and refreshing the browser should show any updates that have been made. Below is the
index.html file we will be working with:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6
document.write("")command is the most basic way to write something to the screen. The
alert("")command will display text in a dialog box that pops up on the screen.
Linking a seperate JS file into HTML can be helpful for organization and is a simple process. Create another file in the same directory as the
index.html file and name it something like
script.js. You can name it whatever you want, it just needs to end with the file type
.js. To link the
.js file into the HTML file, we will add the following code into the
1 2 3 4 5 6 7 8 9 10
Let's start with a blank HTML file, like the one from above, that links to an outside JS file. In that JS file, let's add the following:
documentcommand refers to the HTML document that the entire file is linked to. The
write()command let's us write whatever we want to the HTML document. We can write plain text or actual HTML tags (like the example above). Moving the
<script>tag within the HTML file will determine where that JS will write the HTML.