# CS2 Lab 4 2024, JavaScript 🎰
[<<< Back to main site](https://cs.brown.edu/courses/csci0020/)
<img src="https://hackmd.io/_uploads/rJiyC8J3R.png" width=200>
> **Due Date: Thursday, October 31, 2024**
> **Need help?** Remember to check our Edstem and our Website for TA assistance.
:::warning
**Important Note:** This lab has a longer background and introduction. We recommend that you read through everything and refer back to it as you complete the tasks.
:::
## Introduction
Recall from the previous two labs that HTML defines the structure of the webpage, while CSS defines the style and appearance of the webpage. In this lab, we will be working with JavaScript (JS). JavaScript defines the behavior of the webpage and allows your webpage to change and interact with users, adding a level of sophistication to what you have been working on previously.
## Lab Goals ♣
- Understand the syntax of JavaScript (JS) as well as functions, variables, and callbacks
- Understand what the Document Object Model (DOM) is and how JavaScript interacts with it
- Learn simple JavaScript events: `onclick`, `onmouseover`, `onmouseout`
## Getting Started ♠️
You will be writing your JavaScript files in your VSCode, like you've done with your HTML and CSS files. Once you have finished writing your JS files, you will open the template HTML file in a web browser, which will take care of interpreting what you have written and turn it into an interactive web page.
**This is a harder lab compared to previous labs (based on student feedback) because it is the first time we introduce concepts like variables, conditionals, and programming logic, so start early!** However, understanding JavaScript and specifically functions and variables will help immensely with Python and future programming.
## Learning Javascript ♦
Just like learning any language, it's always best to start with syntax. Here we will briefly talk about how to write a JavaScript program. Below will show you how to declare variables, do arithmetic, and write functions. Some important things to note beforehand:
- All lines (with the exception of those that end with curly braces) end with semicolons
- Be sure to read the documentation and use the links mentioned
### Variables
Sometimes we want to store data for later use. We can do this by declaring a variable. A common way to do this is using the var keyword. For example, we could create a variable `a` with the value 5, and then easily change the value once the variable is created (for example, below we store the value 7 in the variable `a` we previously created).
```javascript=
var a = 5;
a = 7;
```
**Capitalization matters** in JavaScript:
```javascript=
var a = 6;
var A = 3;
```
In the code block above, `a` and `A` refer to different variables.
### Arithmetic
JavaScript allows you to quickly perform basic arithmetic operations. Some of these operations are:
- `+` → addition
- `-` → subtraction
- `*` → multiplication
- `/` → division
For example,
```javascript=
var a = 7;
var b = 6;
console.log(a + b)
```
would print the value `13`. (`console.log()` just prints out whatever is inside for us to see).
**Link to resources:** https://www.w3schools.com/js/js_arithmetic.asp
### Conditionals
Depending on different conditions, we might want our website to behave differently. For example, if it's nighttime we might want to shift our website to night mode. To do this, we can use a conditional if-else statement like below. The if-else statement uses a *condition*, something that’s either true or false, to determine what will happen.
```javascript=
if (<condition>) {
// if the condition is true do this
} else {
// if the condition is false do this
}
```
`if (<condition>)` is true, then the portion of code between the first two curly brackets in the first section is run. `else`, the code in the second portion between the second set of curly brackets is run.
The following syntax is used for comparisons that you might want to make:
| JS Code | Meaning|
| -------- | -------- |
| `===` | equal |
| `!==` | not equal |
|`<=` |less than or equal|
| `>=` | greater than or equal |
| `<` | strictly less than |
| `>` | strictly greater than |
**Example 1**:
```javascript=
var a = 5;
var b = 7;
if ( a <= b) {
console.log("a is less than or equal to b");
} else {
console.log("a is not less than or equal to b");
}
```
In this example, the if condition (less than or equal to) is true for the two variables *a* and *b* so the first portion of the code is run and ``"a is less than or equal to b"`` is printed to the console:
**Example 2**:
```javascript=
var a = 5;
var b = 7;
if ( a === b) {
console.log("a is equal to b");
} else {
console.log("a is not equal to b");
}
```
In this example, the condition would evaluate to false because a and b are not equal. Therefore only the code within the brackets for the else block will run and print ``"a is not equal to b"``.
**Link to resources:** https://www.w3schools.com/js/js_if_else.asp
### Functions
When we write code, there are sometimes chunks of code that we want to use multiple times in different places, but it would be a pain to copy and paste what you’ve already written EVERY time you want to re-use that chunk of code. That’s where functions come in. A **function** is a block of code that is meant to be called and executed in multiple places.
**Example 1**:
A function can have an input and an output. For example, we can have an add function that adds two numbers `x` and `y`, and returns their output. Consider the following code:
```javascript=
function add(x,y) {
return x + y;
}
var z = add(1,2);
```
:::spoiler **Check:** What does `z` equal?
`z = add(1,2) = 1 + 2 = 3`, therefore `z = 3`!
:::
The **function definition**, line 1, is what defines the name and parameters of the function. This function name is `add` and it needs two **parameters**, `x` and `y`. We can also think of parameters as inputs to our function (so we input `x` and `y`, and output `x+y`).
The **function body**, line 2, is what the function actually does. In this case, the function calculates the sum of the given parameters (`x` and `y`) and returns it.
The **function call**, line 4, is outside of the function itself, and it’s what actually tells the browser to execute the function. ==***If you don’t have a function call, your function body won’t be executed!***== In this case, we are calling the function `add`, passing in 1 as `x` and 2 as `y`.
**Example 2**:
A function can also take no input and return nothing:
```javascript=
function hello() {
console.log(“hello world”);
}
hello();
```
This function takes in no arguments (still needs the parenthesis) and just prints out "hello world". It doesn’t return anything either. Again, line 4 above is the **function call**.
When you write a function, whether it returns something depends on what you need it for. If you want to use the result of the function later in your program, you should include a return statement to save and use that result.
:::warning
Even if a function doesn’t have arguments, to call the function you must still add the parentheses.
:::
**Link to resources:** https://www.w3schools.com/js/js_functions.asp
## Tasks ♥️
:::info
**Task 0** Double click your `CS2` folder on your desktop, and create your folder for `JavaScript`. Then, create a new folder inside called `JavaScript Lab`. All your files for this JavaScript Lab should live in this folder.
:::
### Writing JavaScript
For this lab, we will be using both Visual Studio Code (VSCode) and Google Chrome. To write JavaScript in the Google Chrome console:
:::info
**Task 1**
1. Open up a new Chrome Window.
2. Right click (two finger click on Mac) on the webpage. Click on the "Inspect" option. The right side of your screen should look like this:
![](https://hackmd.io/_uploads/By1jQD0pn.png)
**Note:** After clicking inspect, the console tab should be open. If it’s not, click to open it (circled in red in the above image).
:::
This console is an area where you can write code. While this lab will take you through the steps of how to code in JavaScript, a few general things to keep in mind are:
- When you hit `enter`, your code will be run. If you need to write code that takes more than one line, you can press `shift+enter` to use a new line without running what you have currently written.
- When you run your code by pressing `enter`, you might see another line appear that says `undefined`. This is not an error. It refers to the return value of what you just ran. If a function does not return anything after being called, the console prints `undefined`.
- The console remembers what you have written. To clear the console, either:
- Exit out of the tab, **OR**
- Right click on the console and press “Clear Console History” (“Clear” only removes output on screen)
### Printing
To print something in JavaScript, we use `console.log(`). For example,
```javascript=
console.log(3);
```
would print the number 3 (as seen below).
![](https://hackmd.io/_uploads/SJ1gNw06h.png)
Now it's your turn!
:::info
**Task 2**
In the console, type:
```javascript=
function hello(){
console.log("Hello World!");
}
hello();
```
This should output `Hello World!` to the console. Congratulations, you just wrote your first JavaScript program!
:::
Now, let's move on to working with JavaScript within VSCode.
:::info
**Task 3**
1. Download the [**JS Lab Stencil HTML file**](https://drive.google.com/file/d/18u17YSE0XgAag6o1fTMbly6uSJEjFH3w/view?usp=sharing) and put it into the `JavaScript Lab` folder you made in Task 0.
2. Open the `JavaScript Lab` folder in VSCode
3. Create a new file called lab4.js in the `JavaScript Lab` folder.
4. Open the `homepage.html` file in VSCode.
5. To get your JS file to work with an HTML file, you must link the files together. This is very similar to the way you link a CSS file to an HTML file. Place the following line of code before the closing body tag (`</body>`) in your `homepage.html` file:
```javascript!
<script src="./lab4.js"></script>
```
:::
:::info
**Task 4**
Now it's your turn! Recalling the `add` operation from earlier, create the following functions with the appropriate names in lab4.js:
- `subtract`: subtracts two numbers and returns the result
- `multiply`: multiplies two numbers and returns the result
- `divide`: divides two numbers and returns the result
:::spoiler **Hint**
Remember to use parameters in the parentheses of each function!
:::
:::info
**Task 5**
Write a function called `rnd` that returns a random number between 0 and 255 (inclusive).
- To learn how to generate a random number, check out: https://www.w3schools.com/js/js_random.asp
- You’ll want to use both **`Math.random()`** and **`Math.floor()`**, and this function should look almost exactly like one of the examples above!
:::spoiler **Testing your functions**
If you want to test that your functions work, there are two methods to do this:
1. Try copying and pasting your code (the function definition) in the Google Chrome console, then calling each function. To call a function, make sure you pass in the appropriate arguments within parentheses (or leave parentheses empty if there are no arguments). For example, to call add above, you could write `add(2,3)` which should print out 5.
2. If you have correctly linked your JS and HTML, you can also just open your webpage in Chrome as you would normally, then open the console, and then run your functions. This way, you avoid having to copy code over, because your webpage already knows about the functions you’ve written in your javascript file. For example, if you’ve defined the rnd function in your javascript file and linked your javascript to your html, then you can open the html in chrome, click Inspect and then simply type `rnd()` in the console. When you hit enter, a random number from 0-255 should print out in the console.
:::
### The Document Object Model
Now that we understand JavaScript, we can use it to change the way our website behaves. An important thing to remember from the HTML lab is the concept of nested tags. When structuring an HTML document, tags are nested within each other. This nested structure is called the document object model (DOM).
The DOM is important because it gives us a way of accessing specific elements within the file. We are going to use the DOM to practice changing elements of the website. In JS, the function:
:::success
`document.getElementById(id)`
:::
allows you to get an element with a given `id`. Once you get an element with the `id`, you are able to make changes to its properties (such as text color, background color, etc.).
For example, if the first paragraph has `id="first_paragraph"` in our HTML file (recall a paragraph uses the `<p>` tag) and we want to change the color of the first paragraph text to blue, we can write in our JS file:
:::success
`document.getElementById("first_paragraph").style.color = "blue";`
:::
Now it's your turn!
:::info
**Task 6**
In lab4.js, write a line of code to change the **background color** of the website from blue to any other color. To do this, you should use `document.getElementById` to get the appropriate element (the body), then set the background color of that element to your new color.
>You can look at homepage.html to find what element id to use and you can use this [list of object properties](https://www.w3schools.com/jsref/dom_obj_style.asp) to find what property of that element to change.
:::warning
**Check:** Try opening homepage.html in your Chrome browser to make sure the background color changed correctly!
:::
### Events
Now that we understand how we can change elements using JS, let’s add some interaction with our site!
We can add event listeners to different ids to have something happen when they are clicked (`click`), the mouse is moved (`mousemove`), the mouse is hovered (`mouseover`), etc. Here is a more comprehensive list of events. For this lab, we are going to be focusing on click events, but the general idea applies to using other events.
If we want a function to occur every time an element with a given id is clicked, we can use:
`document.getElementById(“<id>”).addEventListener('click', <function>);`
Note that the id should again be passed in in quotes and the function should just be passed in by name. For example, we can define a function `changeBackgroundColor` that is called every time a button with `id=“button”` is clicked:
```javascript
document.getElementById(“button”).addEventListener('click', changeBackgroundColor);
```
> Note we just use the NAME of the function, we don't put the `()` after it (which calls the function). This is a `reference` to a function.
:::info
**Task 7**
Next, we are going to **add functionality to the effect button**.
The effect button will toggle the visibility of the image. When you click on the effect button, the image should disappear when it is showing and reappear when it's not.
Lets break it down for you:
1. In your javascript file, create a new function called `toggle`. For now, it can be empty.
2. In your javascript file, add an event handler to the effect button. Note that in the HTML, the effect button has an ID of `effect-button`. When the button is clicked, it should call the `toggle` function you just defined.
3. Give functionality to the `toggle` function.
- Use a conditional to check if the image is not visible by checking if the visibility property of the image is "hidden"
* `if` so, you should set the visibility property to "visible"
* `else`, you should set it to "hidden"
* the image you should be changing the visibility of has the id of `toggle-image`
>Hint: the “if else” statement referenced in the conditionals section might be helpful here!
Here’s an example of a condition that you could put inside your if statement to check if the current condition is hidden:
```javascript=
if (document.getElementById("<id>").style.visibility === "hidden") {
// do something
} else {
// do something else
}
```
The triple equal sign is used for conditionals. Here you are basically asking the question: is the visibility hidden? If that question is answered “true”, then you enter the if statement. If it is false, you’ll go to the else statement.
The target attribute you are trying to change within the style is called `visibility`. Note that in the if statement, we use `===` to compare, but if we were trying to set the visibility of an object to something (either "hidden" or "visible"), we would just use `=` for assignment.
:::
## Hand-In 🎲
:::success
**To Hand-In Lab 4**:
Come to hours and show your TA the following:
1. `Hello World!` printed in your console (Task 2)
2. The functions `subtract`, `multiply`, `divide`, and `rnd` in your `lab4.js` file (Tasks 4 & 5)
3. Your homepage with a background color other than blue (Task 6)
4. An image that disappears and reappears when you click (Task 7)
Congrats! You just finished your CS2 JavaScript lab! :slot_machine:
:::
<hr />