JavaScript Refresher – Using JavaScript in HTML

How to use JavaScript in an HTML file

JavaScript is a dynamic loosely typed language which is now the lingua franca of the browser now.

We can add JavaScript to a web page as inline, embedded or in an external .js file. For example

Inline

<input type="button" value="Click Me!" onClick="alert('Clicked');" />

In the above the inline JavaScript will display an alter in response to the button being clicked.

Embedded

The same code as above but with the JavaScript embedded would look more like

<script>
function clicked() {
   alert('Clicked');
}
</script>

<input type="button" value="Click Me!" onClick="clicked();" />

I’ve removed superfluous code but the usual place to put the script is in the section.

External File

If we have a file name (for example) scripts.js then we’d place the scripting code in that file as below

function clicked() {
   alert('Clicked');
}

and in the of the HTML file we’d have the reference to the script

<script type="text/javascript" language="javascript" src="scripts.js"></script>