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.

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)

<div onclick="randomBGColor()">
  <p>
    Click on any text, see what happens.<br />
    This uses an <em>inline</em> script to do the work (no separate .js file).
  </p>
</div>

<script>
  function randomBGColor() {
    let r, g, b;
    r = Math.floor(Math.random() * 256);
    g = Math.floor(Math.random() * 256);
    b = Math.floor(Math.random() * 256);
    document.body.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
  }
</script>

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):

index.html
<script src="script.js"></script>
<div onclick="randomBGColor()">
  <p>
    Click on any text, see what happens.<br />
    This uses an <em>inline</em> script to do the work (no separate .js file).
  </p>
</div>

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:

script.js
function randomBGColor() {
  let r, g, b;
  r = Math.floor(Math.random() * 256);
  g = Math.floor(Math.random() * 256);
  b = Math.floor(Math.random() * 256);
  document.body.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}

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:

<script src="myScriptFile.js"></script>

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):

index.html
<script src="script.js"></script>

<p><strong>Please select one of the following:</strong></p>
    
<button onclick="getName()" style="padding:15px">Name</button>&nbsp;&nbsp;
<button onclick="age()" style="padding:15px">Age</button>&nbsp;&nbsp;
<button onclick="roll()" style="padding:15px">Roll a Die</button>

<p>
<div id="output"></div>  <!--  <<  This is where the output will go  -->
</p>

Javascript File:

script..js
// Take a look at this function to see how to edit HTML
function output(stringToOutput) {
  // Change the contents of the <div> with id="output"
  document.getElementById("output").innerHTML = stringToOutput;
}

// Roll a 6-sided die
function roll() {
  output(Math.floor(Math.random() * 6)+1);
}

// Ask the user for their name
function getName() {
  let input = prompt("What is your name?");
  if (input !== null && input.trim().length > 0)
    output(`Nice to meet you, ${input}`);
  else
    output(`You don't want to tell me your name?`);
}

// Ask the user for their age
function age() {
  let input = Number(prompt("How old are you?"));
  if (input !== null && !isNaN(input) && input > 0)
    output(`You are ${input} year(s) old already?`);
  else
    output(`Don't be ashamed of your age, tell me!`);
}

Last updated