Wouldn't it be fun if we could interact with our webpage? When the browser loaded this webpage, it asked you for your name and your favourite color. It then displayed a message in your favourite color with your name in it! Other interactions could be when we click a button, for example:
Click me!
A common programming language that allows us to interact with web pages is Javascipt.
In this introduction to Javascript we will focus on 3 things:
<!doctype html>
<html>
<head>
<title>My page</title>
<style>
p{font-size:14px;}
</style>
</head>
<body>
<p>Welcome!</p>
<script>
</script>
</body>
</html>
As you can see, the script tags go at the bottom of the body section. In fact, as you get more experience with javascript, you will know that the script tags can go anywhere in your document depending on the situation.
To get us started, we will put the script tags at the bottom of the body section.
Javascript has some useful functions that we will use to mess around with data. One of them is the prompt() function. We can use it to get data from the user like this:
prompt("Enter your name:");
So, it's super easy to ask the user to enter data from the keyboard. However, now we need to store the data so that we can process it and display a result somewhere on the webpage later.
Let's create a variable and give it a name. This can be used to store the data:
var yourName;
Now we just have to assign the data from the user to the variable called yourName.
var yourName;
yourName = prompt("Please enter your name?");
A webpage usually has many elements on it. There could be some <p> tag elements, or some <img> elements or maybe even an <iframe> element.
What we need is an element that can be targetted by javascript to display the data stored in the variable. We could use a <p> element for this.
But what if there are many <p> elements on the webpage? How will javascript know which one to use? The trick is to give the element that you want to use a unique id. This is easy:
<body>
<p>Your name is displayed below!</p>
<p id = "name"></p>
</body>
Notice that the second <p> element is empty, but it has a unique id. When our javascript runs, it will target that element and put some data inside it.
So, how can we target the element that will display the data? Back to javascript, we will use another very common function:
document.getElementById("name")
This javascript targets the element in the webpage that has the id name.
Now, we can push some information/data into the targetted element like this:
document.getElementById("name").innerHTML = yourName;
where yourName is the variable that we created to store the data from the user.
Here is the final html document:
<html>
<body>
<p>Your name will be displayed on the next line!</p>
<p id = "name"></p>
<script>
var yourName = prompt("Please enter your name");
document.getElementById("name").innerHTML = yourName;
</script>
</body>
</html>
So, we can see that HTML, CSS and Javascript work together to create engaging webpages.