So far, our site is static and has no interaction. There's no way to make our page do anything.
Let's use our terminal to create a new folder in our project called
js. Within that folder, create a file called
Next, let's go into our
index.html file and link
scripts.js. It will be similar to how we linked our CSS file. However, we'll need to use a slightly different format. Update the
<head> element in
index.html to look like this:
... <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="css/styles.css"> <script src="js/scripts.js"></script> <title>Epicodus Workshop Project</title> </head> ...
We use the
<script> element and a
Now let's open our
scripts.js file and add some code.
Save your files and reload the page in the browser:
Our page just said hi. The box that popped up is called an alert.
alert("Hello World!");. Let's break this down and talk about what's happening here. This is something called a function. Simply put, a function is a piece of code that carries out an operation. We can use all kinds of pre-existing functions and we can even define our own functions.
Here, we're calling a pre-existing function called
alert(). Notice the parentheses? In programming, we call those parens. They're a good clue that the piece of code we're looking at is a function. The parens have a special use, which is to collect data that the function itself will then use. The information passed into parens is called an argument. In the case of our function here, we're giving it the argument
"alert" and the function
alert() use the same set of letters so we need a way to differentiate them. For a function, we use parens. For a piece of text, we use quotes. A piece of text contained within quotes is called a string. When we write code, everything that needs to be treated as a piece of text must be formatted as a string.
2 and the string
"2". The first is an integer while the second is a string. Let's see how this works.
Clear the contents of
scripts.js and replace it with the following lines of code. Pause before you reload your page and try to predict what we might see.
alert(2 + 2); alert(4 * "2"); alert(8 + "2");
We will get the following alerts:
The first two make some sense. However, the third doesn't actually add the two numbers together.
"2"from a string to an integer and gave us the result. It inferred the data type.
8and tried to add the string
+. If we were to add
"trout"together, we would get
Try experimenting with different combinations of strings and integers. Guess what will happen before you refresh your page.
Lesson 4 of 8
Last updated more than 3 months ago.