Intro to Web Development
Share
Explore

Make it interactive

Use JavaScript to make your website interactive
JavaScript (JS)
JavaScript is a programming language that can add interactivity to your website. For example, you can use JavaScript to make things happen when the user clicks a button or enters information into a form.
The <script> tag
We will be writing our JavaScript in the script.js file. If you look at the index.html file, you'll see this line of code in the <body> element.
<script src="script.js"></script>
The <script> tag does the same job for JavaScript that the <link> tag does for CSS. It tells the browser to apply the code in script.js to the HTML file.
Note: Make sure the <script> comes right before the closing </body> tag! This ensures that the rest of the document elements have been loaded before the script is run.
⭐️ Step 0: Show an alert message
In script.js, add the following line of code. Feel free to replace "Hello, world!" with a message of your choosing.
alert("Hello, World!");
Then, click the "Run" button. Your message should show up in a pop-up alert. Congrats! You've written your first line of JavaScript.
In the next section, we'll learn a little more about programming basics before diving into writing JavaScript that interacts with the HTML and CSS on our web page.
Programming crash course
For those of you who already know a programming language like Java or Python, feel free to skim this section or skip to the "Make your webpage interactive" section.
Variables
A variable is something that can change. We use a variable to store a value that can change, and we can access the current value of a variable at different points in our program.
Example: If we're programming a game, a variable could keep track of the player's current score.
In JavaScript, we can define a variable with the keyword let:
let myVariable;
In this example, we have declared the variable named myVariable, but we haven't assigned it a value yet. Because of defaults in JavaScript, its value will be undefined for now. We can easily assign a value to it:
myVariable = 10;
Alternatively, we can define a variable with a starting value:
let myVariable = 10;
Now, we've declared myVariable and it starts off with value 10. Later on in our program, we can access myVariable and use its current value. For example, we can do:
let otherVariable = myVariable + 5;
This is effectively the same as doing let otherVariable = 10 + 5 because the value of myVariable is 5 when we read its value.
We can change the value of our variables at any time during the program. For example, this is how we would increase the value of myVariable by 2.
// The following two lines of code are equivalent.
myVariable = myVariable + 2;
myVariable += 2;
Whenever we access variables, we'll always get their most current value.
Data Types
You can store different types of data using variables.
Search
Data Type
Explanation
Example
1
String
A string of text. You must enclose the text with quote marks to indicate that it is a string.
let myVariable = 'superposition hackathon';
let myOtherVariable = "also a string";
2
Number
A number (can be an integer or rational number)
let myVariable = 42;
let myOtherVariable = 0.25;
3
Boolean
A true or false value. The words true and false are special keywords in JavaScript and do not need to be surrounded in quotes.
let myVariable = true;
There are no rows in this table
Arrays
An array is a data structure that represents a collection of elements. You can store all sorts of data types in an array. You can have an array of numbers, an array of strings, etc.
Example: If we're programming a grocery list app, then we could use an array to keep track of all the grocery items that the user wants to buy.
In JavaScript, you can declare an array like this:
let myArray = [1, 4, 9, 16];
Now we have a variable myArray whose type is an array of numbers.
Arrays in JavaScript have several properties and functions that we can use. Most importantly:
We can read an individual element in the array using the syntax myArray[index]. Each element in an array has an index that is their numerical position in the array. The first element has an index of 0; the second element has an index of 1; etc. So, if we want to read the first element of myArray, we can get that by doing myArray[0]. We can index into an array using any number between the square brackets, but if we try to access an index that does not exist in the array, the value returned will be undefined.
We can overwrite any element in the array. Above, we described how to read an element in the array. Similarly, we can overwrite an element in the array using its index. To replace the second value in myArray, we can do myArray[1] = 25.
We can get the number of elements in the array. Every array has a length property. For our example, myArray.length will evaluate to 4.
We can add an element to the array. Every array has a push function that lets us add an element. If we do myArray.push(36) then our array will now be length 5, and 36 will be the fifth element.

You can read more about the available JavaScript array functions
.
Functions
A function is a list of instructions that always runs together. Functions are the building blocks of programming. Similar to a math function, like f(x) = x + 5, these programming functions can take input(s) and can return an output. Functions are useful because they simplify programs and allow programmers to reuse their code.
Example 1: In Step 0, you used the alert(...) function without needing to the details of how it was implemented!
Example 2: In my game, if I needed to calculate the distance between two points in multiple places in my code, I can write a distance function that takes the coordinates of the two points as the inputs and returns the calculated distance. This way, I only have to write the distance code once, but I can call the distance function in multiple places.
In JavaScript, you can define your own function like this:
function square(x) {
// The code below will be run every time we call this function.
return x * x;
}
Now, we have defined a function named square.
There are several key points to note in this example:
In our code, we reference our function using its name, square.
The function's inputs are within the parentheses next to square: in this case, our function takes only one input, x. The function then returns x * x.
When we want to use our square function, we must give the expected input, which is 1 number.
In our code, when we can call our square function, it will be the same as replacing that function call with the value returned by the function. What this means is let squared4 = square(4) is the same as doing let squared4 = 16, because square(4) is equal to 16.
Conditionals
A conditional is a statement that says if a certain condition is true, then run some code.
Example: If our "score" variable is less than or equal to 0, then tell the user "You Lost!".
In JavaScript, you can write a conditional statement like this:
if (score <= 0) {
alert("You lost!");
}
The expression within the parentheses next to if is called the condition. Conditions must be boolean expressions (i.e. they must evaluate to true or false).
Notice that in our first conditional, the condition is score <= 0. This <= is a comparison operator that means "is less than or equal to".
Here are some of the useful comparison operators to know:
Search
Comparison Operator
Meaning
1
<
less than
2
>
greater than
3
<=
less than or equal to
4
>=
greater than or equal to
5
!=
not equal to
6
==
equal to (without type checking)
7
===
equal to (with type checking)
There are no rows in this table
7
Count

The difference here between the two equality operators is that === performs type checking, meaning that the operator will return false if the left and right sides are not of the same data type, whereas == will convert the left and right sides before checking equality, if they are not yet of the same data type.
Another useful concept is the else block. Sometimes, you want to run some code if a condition is true, and run different code if the condition is false. We can do that like this:
// playerIsReady is a boolean value
if (playerIsReady) {
// playerIsReady is true, so we run this code
startGame();
} else {
// playerIsReady is false (i.e. not true), so we run this code instead
showInstructions();
}
Loops
A loop is a way for us to repeatedly run code.
One type of loop is a for-loop. When we use a for-loop, we specify exactly how many times we want to repeat the code inside the loop.
Example: We could use a for-loop in our grocery list app to send a reminder to the user for each item on their list. The number of repetitions is the number of items on their grocery list.
In JavaScript, you can define a for loop in several ways. Here is the basic structure:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed once before running the code block.
Statement 2 defines the condition for running the code block.
Statement 3 is executed every time after running the code block.
In the example below, we use the i variable as a counter that begins with value 0. As long as i < 5 we will run the code block. After each iteration, we increase the value of i by 1.
for (let i = 0; i < 5; i++) {
// The code below will be run 5 times
alert('Your dinner is ready!');
}
We can also use a for-in loop to iterate through all the elements in an array.
let myGroceries = ['apple', 'banana', 'chili'];
for (food in myGroceries) {
alert('Don't forget to buy ' + food);
}
The first time the code block is run, the value of food will be 'apple'. The second time the code block is run, the value will be 'banana' and the third time it will be 'chili'.
Make your webpage interactive
⭐️ Step 1: Access your HTML document
In order to make your webpage interactive, you need to access elements in your HTML. In your JavaScript file, you can access the HTML document (also known as the Document Object Model or DOM) through the document variable.
Add the following code to your script.js (feel free to remove anything there that you no longer want). This line of codes tells the browser to print the document model to the console.
console.log(document);
If you open up the "Console" tab in the developer tools and click "Run" in Repl, you'll see the document object printed to the console. You can interact with it to see the contents of your web page.
Screen Recording 2020-02-29 at 20.29.gif
⭐️ Step 2: Access specific HTML elements
The document object has several functions that can help you access specific HTML elements on the page.
The notation that we use to call a function that "belongs" to some object is myObject.functionName(...).
let body = document.getElementsByTagName("body")[0];
let div = document.getElementById("some_id");
let divs = document.getElementsByClassName("some_class");
You can even grab elements using CSS selectors.
let div = document.querySelector("div#some_id");
let divs = document.querySelectorAll("div.some_class");
Once you have a reference to a specific HTML element, you can access its different properties.
The notation that we use to get the value of an object's property is myObject.propertyName.
For example, if I have a text input with id "my-text-input", then I can get the user input by accessing the value property of the text input element.
let input = document.getElementById("my-text-input");
let text = input.value;
I can also update the text in one of my <p> elements like so:
let myTextElement = document.getElementsByTagName("p")[0];
myTextElement.innerText = "Here is the updated text!";
Use one or more of the functions above to assign a specific HTML element on your page to a variable. A variable that corresponds to your button element would be a useful 😉
Debugging tip: If your code is not returning the correct HTML elements, make sure the <script> element in your index.html file comes right before the closing </body> tag. This ensures that the other document elements have been loaded before the script is run.
⭐️ Step 3: Add an event listener
With JavaScript, you can respond to events that happen on the page. A common event you might want to handle is a click event.
let button = document.getElementById("mystery_button");

button.addEventListener("click", function() {
alert("Surprise!");
});
When a user clicks on the button with id mystery_button, an alert message will pop up saying "Surprise!".
Add your event listener to an element on your page.
is a list of other events you can add to your web page. Keyboard and mouse events are the most commonly used.
🍦Challenge: Respond to user input
Add some form elements and a <button> to your web page if you haven't already. Make your webpage do something interesting when the user clicks on the button. Here are some ideas:
Have the user enter their name into a text box and show an alert that says "Hello, [name]!" when they click the button.
Make a multiple choice personality quiz (like the ones from BuzzFeed)
Make a to-do list
Create an educational game where people guess the answer to questions about some topic (e.g. how to save the environment)
Make a typing quiz that calculates your words typed per minute
JavaScript Tasks
6
Search
Task
Status
1
Show an alert message using JavaScript
Not Started
2
Access your HTML document using JavaScript
Not Started
3
Access specific HTML elements using JavaScript
Not Started
4
Add an event listener using JavaScript
Not Started
5
🍦Challenge: Respond to user input
Not Started
No results from filter
Next Section ➡️

Share
 
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.