Where to store JavaScript

As with CSS, JavaScript can be placed inside HTML elements, within an HTML file, or in a separate file.

 

Inline JavaScript

The JavaScript code to respond to an event is written inside the HTMl element.

This is only suitable for very simple scripts.

HTML body
1
<button onclick="alert('You clicked me!')">Click Me</button>

Internal JavaScript Code

All JavaScript functions are written in a <script> block, often placed inside the <head> block for maintainability. A script block can contain multiple functions.

Events then call these functions.

Note: Program/Text editors will use syntax highlighting for HTML, leaving the <script> blocks unformatted – and harder to debug.

HTML head
1
2
3
4
5
<script>
    function showCopyright() {
        alert("This page is copyright A Person 2021");
    }
<script>
HTML body
1
<button onclick="showCopyright()">Copyright</button>

External JavaScript File

If you will use the same scripts across several pages, then save them in a separate file – myscripts.js

Add a link to the file in the <head> of the HTML:

myscripts.js
1
2
3
function showCopyright() {
    alert("This page is copyright A Person 2021");
}
HTML head
1
<script src="myscripts.js"></script>
HTML body
1
<button onclick="showCopyright()">Copyright</button>