Getting Started With JavaScript
What can JavaScript do?
The JavaScript programming/scripting language is deeply embedded into the web. It allows websites to do more than just display static content, the content can change even after a web page has been loaded in the browser.
JavaScript is usually behind features such as:
- CSS style changes when a mouse moves over an element
- Responding to a click (add to cart button, close modal etc)
- Rotating image carousel
- Animations
- Adding/removing content such as a TO-DO list
- Calculations
- Restricting access to only users signed in
- And so much more
Generally, JavaScript can add, remove, and update any HTML elements or CSS styling without a browser refresh.
This course covers a practical introduction to JavaScript while building a project, a more comprehensive course is available here if required.
Where to add JavaScript
In a similar way to CSS, we can add JavaScript in more than one location. It can be placed in the HTML head
or body
section, within script
tags:
<!-- JavaScript in the head -->
<head>
<meta name="viewport" content="width=device-width">
<title>Online Store: Home</title>
<script>
alert("JavaScript is working!");
</script>
</head>
<!-- JavaScript in the body -->
<body>
<!-- HTML content -->
<script>
alert("JavaScript is working!");
</script>
</body>
One of the benefits of adding to the end of the body
section is the HTML content can load first, avoiding any potential slow down in page load times. It also avoids JavaScript attempting to select any elements that have not yet been created.
The alert()
method used will display a message alert box in the browser.
Inline JavaScript
JavaScript code can also be placed inline with HTML elements:
<body onload="alert('JavaScript is working!')">
<header>
<h1>Online Store</h1>
The onload
event will run the code when the web page has finished loading.
External JavaScript file
To avoid mixing HTML with JavaScript we can put it inside of an external file. The file name is up to us, but must include the .js
file extension. Create a new file named script.js
in the project folder:
online-store/
├── images
├── dashboard.html
├── index.html
├── script.js
├── styles.css
At the bottom of the <body>
section, insert the <script>
element. Providing the file path to the external file with the src
attribute:
<script src="script.js"></script>
</body>
</html>
Add this to both the index.html
and dashboard.html
pages. This means the code will be applied.re-used for both pages. Test this works by alerting a message:
// script.js
alert("JavaScript is working!");
The file can be linked in either the head
or body
but the head
has the same limitations described above.
The alert can be removed after testing.