Where To Add JavaScript
We are going to begin right at the beginning and take a look at exactly where we can add JavaScript into our files. Previously, we have typed code directly into the console. But realistically, it's almost always wrote in our own files.
So, where do we start?
Open the project folder
In our starter files, open the index.html page from this lessons folder:
01.JavaScript Basics > 01.Where to add javascript
Many of these sections only have basic boilerplate code so we can add our code to them. We need something to work with such as a page heading:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Where to add JavaScript</title>
</head>
<body>
<!-- add the following line: -->
<h1>Where To Add JavaScript?</h1>
</body>
</html>
You can open the index.html in the browser by double clicking the file in the project folder.
If using Visual Studio Code, you can also right-click the file in the side bar > copy path > paste into browser.
Also remember to do this each time we move to the next folder, or you make any changes.
The id
attribute
Next we can add a unique id
to this heading:
<h1 id="title">Where To Add JavaScript</h1>
The id
attribute name should be unique and only occur once per HTML
document.
Inserting script
into the body
section
To use JavaScript, we first insert the script
tags:
<body>
<h1 id="title">Where To Add JavaScript</h1>
<script></script>
</body>
Adding these at the bottom of the body
is only one location we can use JavaScript and we will look at more soon.
Earlier we selected an element with $0
, this $0
only works in the console so in place we used a method called getElementById
. We can again use that here inside the script
tags, first by selecting the HTML
document:
<script>document.getElementById("title")</script>
And we can also use the same technique's as earlier such as changing the innerText
:
document.getElementById("title").innerText = "Text changed";
Remember to save the file and refresh the browser to see any changes.
And also changing the text color:
document.getElementById("title").style.color = "red";
Inline JavaScript
Another way of adding JavaScript is inline, as you can do with inline CSS. This is a way of adding JavaScript directly into the opening tage of a HTML
element, similar to when we added the id
attribute.
Let's add an onclick
event handler to run some code when the mouse clicks on an element. We will look at event handlers in more detail later on:
We have already looked at events previously with onmouseover
. This ran a function when the mouse passed over an element.
<h1 id="title" onclick="alert('clicked')">
Where To Add JavaScript?
</h1>
This will display an alert box with the text of 'clicked' after clicking on the heading.
Using script
in the head
section
We can add as many script tags as we want, and they can also be located anywhere on the page, including the head
section. Cut the existing script
section from the body
and paste into the head
section:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Where to add JavaScript</title>
<!-- move script to head section -->
<script>
document.getElementById("title").innerText = "Text changed";
document.getElementById("title").style.color = "red";
</script>
</head>
<body>
<h1 id="title">Where To Add JavaScript</h1>
</body>
</html>
If you refresh the browser, you will see no update to the text. We can see a clue to why inside the console (browser > right click > inspect > console tab):
Uncaught TypeError: Cannot set properties of null (setting 'innerText')
This is because a HTML document is loaded in order from top to bottom, so the script
in the head
is loaded before it even knows the title
element exists, causing the error.
So adding scripts into the head
which need to access the DOM elements will cause a problem.
This is why we often see JavaScript at the end of the body
section, so it allows the elements to be loaded first, and does not block the HTML
from loading onto the page.
You will however see some third-party JavaScript libraries which need the script
to be loaded into the head
section for the library to function correctly, and there are also some more modern approaches to help with this.
JavaScript files
These third-party libraries, along with our own code are usually separated into their own script files. And we do this by creating a new file, with the .js
extension:
Create a new file: script1.js
alongside the index.html
.
Your folder directory should now look like this:
index.html
: Cut the contents from between the script
tags.
index.html
: Leave the remaining <script></script>
tags in place.
script1.js
: Paste the contents directly into this file. We don’t need to use the script tags when working in a JavaScript file.
In the index.html
, using the remaining opening <script>
tag, we link a .js
file using the src=''
attribute:
<title>Where to add JavaScript</title>
<!-- add the file path the script using the src attribute: -->
<script src="script1.js"></script>
</head>
In the browser we still have the same issue since nothing has really changed, we are still trying to load the JavaScript before the HTML has been loaded.
Leaving us with some options to resolve:
- We can write some custom JavaScript to wait until the HTML loads first.
- The <script> can be moved to the bottom of the <body> section to ensure it loads after the HTML.
- We can use the async or defer attributes, this is covered in the next lesson.