# Calling a JS Function

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*](https://www.w3schools.com/js/js_events.asp) and react based on the developer's code. [W3Schools](https://www.w3schools.com/js/js_events.asp) has a great rundown of events in Javascript / HTML.

![Illustration by author](https://docs.google.com/drawings/d/e/2PACX-1vQJJuympwm3B7fNWkmAtD6DhNdQcjM1A1MG8kKfMzpfWyYyM4NUlBNSCOHvt2TzuzZriIZyklKAHink/pub?w=502\&h=177)

&#x20;A list of all events is [available online](https://www.w3schools.com/jsref/dom_obj_event.asp). 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](https://onclickExample1--matthewbrash.repl.co))

```markup
<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?**

![](https://docs.google.com/drawings/d/e/2PACX-1vR3U7zi2GzTo6T6OCOwA-iNrGygzPVgJRgOZiz8Ow6kFPsrsh8MkCjYaSVetf28uCwbaYcAuPs2LcHl/pub?w=810\&h=431)

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

{% code title="index.html" %}

```markup
<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>
```

{% endcode %}

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:

{% code title="script.js" %}

```javascript
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})`;
}
```

{% endcode %}

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:

```markup
<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](https://External-JS-Example--matthewbrash.repl.co))

#### HTML File (body):

{% code title="index.html" %}

```markup
<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>
```

{% endcode %}

#### Javascript File:

{% code title="script..js" %}

```javascript
// 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!`);
}
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.brash.ca/unit-4/calling-a-js-function.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
