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.

<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.

<script>
    function showCopyright() { 
        alert("This page is copyright A Person 2021"); 
    }
<script>
<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:

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