We've done a good job of building a simple page, and adding some styling to it. However, nothing is interactive, and it remains static - there is no way to make the page do anything.
Let's change that.
Can you remember the commands we used earlier to create folders and files?
Let's use our terminal to create a new folder in our project called
Within that folder, create a file called
Once they exist, let's go into our index.html file and link scripts.js. It will be similar to how we linked our CSS file, but we'll need to use a slightly different format. Arrange your HTML in index.html so that the
<head> element looks 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.
After you save your files, reload your HTML, and we should get a nice interaction with the webpage.
Isn't that nice? Our page 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 parenthesis? In programming, we call those parens, and they're always a good clue that 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. In the case of our function here, we're giving it the phrase
"alert" and the function
alert() would use the same set of letters, so we need a way to differentiate them. For a function, we used 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.
String is a data type. There are others. Numbers, for example, are called integers. This is because there is a difference between the number
2 and the string
"2". Let's see how this works.
Let's change our scripts.js to see data types interact. For now, we'll keep using our
alert() function. 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 were alerted with
How strange. What happened?
"2"from a string to an integer and gave us the result. It inferred the data type.
8and tried to add the string
+. Makes sense, right?
In our next lesson, let's take this functionality and apply it to do something useful on our page.