or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing
xxxxxxxxxx
CS2 Lab 4 2023, JavaScript 🎰
<<< Back to main site
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →Important Note: This lab has a longer background and introduction information. 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 ♣
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:
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 variablea
we previously created).Capitalization matters in JavaScript:
In the code block above,
a
andA
refer to different variables.Arithmetic
JavaScript allows you to quickly perform basic arithmetic operations. Some of these operations are:
+
→ addition-
→ subtraction*
→ multiplication/
→ divisionFor example,
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.
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:
===
!==
<=
>=
<
>
Example 1:
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:
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:
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
andy
. We can also think of parameters as inputs to our function (so we inputx
andy
, and outputx+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
andy
) 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 asx
and 2 asy
.Example 2:
A function can also take no input and return nothing:
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.
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 ♥️
Task 0 Double click your
CS2
folder on your desktop, and create your folder forJavaScript
. Then, create a new folder inside calledJavaScriptLab
. 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:
Task 1
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:
enter
, your code will be run. If you need to write code that takes more than one line, you can pressshift+enter
to use a new line without running what you have currently written.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.Printing
To print something in JavaScript, we use
console.log(
). For example,would print the number 3 (as seen below).
Now it's your turn!
Task 2
In the console, type:
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.
Task 3
JS Lab Stencil HTML file
and put it into theJavascript_Lab
folder you just made.</body>
) in your homepage.html file: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 resultmultiply
: multiplies two numbers and returns the resultdivide
: divides two numbers and returns the resultHint
Remember to use parameters in the parentheses of each function!
Task 5
Write a function called
rnd
that returns a random number between 0 and 255 (inclusive).Math.random()
andMath.floor()
, and this function should look almost exactly like one of the examples above!Testing your functions
If you want to test that your functions work, there are two methods to do this:
add(2,3)
which should print out 5.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:
document.getElementById(id)
allows you to get an element with a given
id
. Once you get an element with theid
, 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:document.getElementById("first_paragraph").style.color = "blue";
Now it's your turn!
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.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 withid=“button”
is clicked: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:
toggle
. For now, it can be empty.effect-button
. When the button is clicked, it should call thetoggle
function you just defined.toggle
function.if
so, you should set the visibility property to "visible"else
, you should set it to "hidden"toggle-image
Here’s an example of a condition that you could put inside your if statement to check if the current condition is hidden:
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 🎲
To Hand-In Lab 4:
Come to hours and show your TA the following:
Hello World!
printed in your console (Task 2)subtract
,multiply
,divide
, andrnd
in yourlab4.js
file (Tasks 4 & 5)Congrats! You just finished your CS2 JavaScript lab!
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →