Calling a JS Function

Interaction between HTML and Javascript requires a function to be called.

When someone knocks on your door - that is an event that you would react to (assuming you are home). Most HTML tags (not all) can listen for an event or multiple events and react based on the developer's code. W3Schools has a great rundown of events in Javascript / HTML.

Illustration by author

A list of all events is available online. The more commonly used events are onclick, onload, onmouseover, and onkeydown.

Inline onclick Example

Let's look at a simple example of changing the background colour of the page to a random value whenever the user clicks an area of text: (live example here)

What does that code do?

How would that webpage react if you used onmousemove instead of onclick?

External onclick Example

We can separate our Javascript into an external file and load it with the HTML file. Here is the same example as above, separated into two files (only the body of the HTML is shown here):

Notice the <script src=...> tag on line 1, above. This tells the browser to also load the contents of that file into memory for running script commands. Here's the script file:

This program will function identically but has a nice separation of HTML vs. Javascript. For quick scripts and minor amounts of code, inline Javascript will do. It is a better practice, however, to host your Javascript code in a separate file and link to that file in your HTML document:

Example 3 - Multiple Functions

This next example uses an external JS file with multiple functions required to interact with the HTML file. (Live example here)

HTML File (body):

Javascript File:

Last updated