Learn JavaScript by Building a Dice App

Websites are more than jus text, images and links to other pages. They can be interactive. You might click on a button and see a pop-up dialog box prompting you to enter your email address to sign up for a mailing list. Some web pages are complete applications, like CodePen. How do they do that? Web developers use a programming language called JavaScript to tell the browser when to add, remove or change elements on the page. In this tutorial, I’ll introduce you to JavaScript by showing you how to build a simple dice app.

The app has a blue square in the center with a white number. That’s our die. We’ll use JavaScript to change the number. Beneath the number is the button the visitor can click on to roll the die.

To follow along with the tutorial, it’s best if you understand how HTML works. You’ll need to know how to create elements and add attributes like classes and ID’s.

To get started, login to CodePen and create a new pen. In the settings of your pen, add Bootstrap as an external style.

The HTML Markup

The first thing our app needs is some HTML. Copy and paste the following code into the HTML section of CodePen.

<main class="container d-flex flex-column align-items-center my-5">
	<h1 class="display-1 text-center mb-3">Dice Roller</h1>
	<p class="my-3">
		<span id="result">
			1
		</span>	
	</p>
	<p class="my-3">
		<button class="btn btn-outline-primary">
	</p>
</main>

All the content for our app goes in the container class. That’s a Bootstrap class that’ll make our app look good on different screens sizes. The container element also has a few other classes that align all the elements inside the app to the center of the screen and adds some margin.

At the top of the page is the title. It’s a simple h1 tag with display-1 class for styling.

Next is our die. It’s wrapped in a paragraph tag with some margin. The die element is a span element. span elements are useful when you want to style text a certain way inside of a paragraph tag. They’re like containers (divs) that you should only use for text elements. The span has an ID attribute with a value of result. ID’s are a unique piece of text that we can use to grab the element later.

Lastly, there’s the button that the visitor will click on to rol the die. It’s also wrapped in a paragraph with some margin for spacing. The button uses the Bootstrap btn and btn-outline-primary classes to give the button a white background with blue border and text.

The CSS Styling.

Our app looks great so far, thanks to Bootstrap. But it would be nice if our result element looked a little better. At the start of this tutorial, I described it as being a blue square with white text. Let’s make that happen with a little CSS. Copy the following code into the CSS section on CodePen

#result {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100px;
	height: 100px;
	border-radius: 15px;
	font-size: 50px;
	background-color: cornflowerblue;
	color: white;
}

In CSS, we specify the element we’re styling using a selector. On the first line, we’re selecting the element with the ID of result by adding the pound sign before it. Inside the curly braces, we specify the styles. The first three lines ensure that the text is centered in the element. Then, we set the width and height to 100px, that makes our square. The border-radius gives the corners a slight rounded edge. Next, we set the font size to be 50px. px is short for pixels, these are different from pt (points) that you might be familiar with from word processors. Finally we set the background-color to a light blue and the color (text color) to white. CSS has a bunch of default colors that you can use. Cornflower blue, a light blue, and white are just two of them.

The Fun Part

With the content and styling out of the way, we can finally get to the fun part. Let’s make this page interactive!

To make our page interactive, we need to tell the browser what to do when the visitor clicks a button. There are two things we want the browser to do.

  1. Get a random number between 1 and 6
  2. Replace the number in the result element with the new number.

This is the procedure we want the browser to follow whenever the button is clicked. Whenever we have a group of related instructions like this, it’s best to place them in a function. To create a function, we start with the function keyword, then add the function name. When naming functions, it’s useful to give them a descriptive that tells you something about what the function does. Our function will be called roll. After the function name, add opening and closing parentheses. Some functions take parameters that will go here, but we’ll get to that later. Lastly, add opening and closing braces with an empty line between them. This is where the instructions for the browser will go

function roll() {
	...
}

Let’s test our function by adding it to the button. To tell the browser that we want it to follow the instructions in the function when the button is clicked, we need to add an onclick attribute to the button element. the onclick attribute should have a value of roll(). When we tell the browser that we want it to follow the instructions inside a function, we say that we’re “calling” the function. When the function executes those instructions, we say that it is “running” the function.

<button ... onclick="roll()">Roll</button>

Now, when you click the button… Nothing happens. That’s because we haven’t put any instructions between the curly braces.

A common way to test that your function is working is to write something to the console. The console is a tool in CodePen and most web browser that web developers use when testing their apps. It allows us to add helpful messages throughout our code to let us know if the app is working as expected or not.

To add a message to the console, we use a function called console.log. This function is built into JavaScript. To set the message, we need to provide the function with a parameter. That’s why we need parentheses when we call a function. For the console.log function to work correctly, it needs the message that we want to print to the console. To provide the message add quotation marks in the parentheses and write your message inside the quotation marks.

function roll() {
	console.log('Roll');
}

CodePen has it’s own console. You can open it by clicking on the “console” button in the bottom right corner of the screen. Now, you can click the button. Once you do that, you should see text appear in the console that says “Roll”.

Note: If you see an error (some text highlighted in red), check that your code is exactly the same as it’s written here, it won’t work otherwise. Before fixing the code, clear the console by clicking the “clear” button in the top right corner of the console section. Once you’ve corrected the code, give CodePen a few seconds. If an error doesn’t appear, you can click the button and see what happens.

Now that we know that our function is being executed when the button is clicked, we can start working on writing the instructions.

Getting a Random Number

The first thing we need our function to do is to get a random number between 1 and 6. But first, we need a place to save that number. Whenever we need to save a number or some other value, we use variables. To create a variable, use the let keyword followed by the variable name. Like functions, this name should be something that will help you remember what the value is for. After the variable name, add an equals sign and then the value. We’ll set the number to 1 for now.

function roll() {
	let num = 1
	console.log('Roll');

}

Now that we have our variable setup, let’s use it in the console.log function. Replace the "Roll" (including quotation marks) with num (our variable name). The browser will know to replace the word num with the number 1 which is the current value of the variable.

function roll() {
	let num = 1
	console.log(num);

}

Now, when you click the button, instead of seing the message that says “Roll!”, you should see the number 1.

Notice how I placed the variable declaration (the line with the let keyword) before the console.log. That’s because the browser works from to p to bottom. If you try to use the variable num before you’ve told the browser what that is, it’ll give you an error.

If you click the button multiple times, you’ll notice that our number never changes. We want it to be different every time. The nice thing about variables is that we can change their value through the function. To get our random number, we’ll use another built in JavaScript function called Math.random. The Math.random function doesn’t take any parameters, but it does give us back a number. When a function gives us back a number or other value, we say tha tit “returns” the value. To use the function, add a new line before the consoeo.log statement. start by using the variable name num followed by an equals sign, tne the function Math.random.

function roll() {
	let num = 1
	
	// Get a random number
	num = Math.random();

	console.log(num);

}

Now when you click the button, you should see a different number in the console each time. but wait, it’s not a whole number, it’s a decimal number. According to the documentation, the Math.random function provides a random number between 0 and 1. That mans we’ll need to do a little extra math to get the number between 1 and 6. Fortunately, the documentation tells us exactly how to do that.

Here’s the example from the documentation.

Math.random() * (max - min) + min;

We already have our random number, so we can replace the Math.random here with num. We also know that the highest (maximum) number we want is 6. However, the documentation warns us that the maximum number is exclusive. That mean’s it’ll never give us the maximum number. So, we can replace max with 7, ensuring that it’s possible for the user to roll a 6. finally, we know that the lowest number we want is 1, so we can replace the min with 1.

On the line after we got the random number, add the following code.

num = num * (7 - 1) + 1;

At first glance, this can be a bit confusing. We’re using because we’re using the num variable on both sides of the equals sing. When the browser executes this line, ti’ll evaluate the left side first. so num still has the value of that decimal we are trying to covert. Once it’s got new value, ti’ll assing it to the num variable, overwriting the old value.

Now, when yo click the button, a number between 1 and 7 should appear in the console. But it’s still a decimal. We only want a whole number. To fix that, we need another function: the Math.floor function. That function will cut off the decimal numbers and leave us with just the whole number.

Add a new line just below the last one, but before the console..og statement. Here, we’ll use the Math.floor function to give the num variable a new value.

function roll() {
	const result = document.getElementById('result');

	let num = 1
	
	// Get a random number between 0 and 1
	num = Math.random();
	
	// Get a rnadom number between 1 and 7
	num = num * (7 - 1) + 1;

	// Remove the decimal
	num = Math.floor(num);

	console.log(num);

}

Now, when you click the button, you should get a nice whole number between 1 and 6.

Updating the Number on the Page.

This is great! we got our whole number printing to the console. But we don’t want it there, we want it to appear on the page in the blue box.

Remember that the blue box has an ID of result. JavaScript comes with a function that can help us grab the element by its ID and change properties of the element. The function for grabbing elements by ID is called document.getElementById. Like console.log it takes a string of text in quotation marks as a parameter. The text between the quotation marks should be the ID of the element we want to get.

Once we have the element, we can change properties on it. To change the text in the element, we need to change the innerText property. We can do that in the same way that we change variable values. Add the following line at the bottom of the function.

document.getElementById('result').innerText = num;

When you click the button, you should now se the number in the blue box change each time.

Final Code

Here is the entire function.

function roll() {

	let num = 1
	
	// Get a random number between 0 and 1
	num = Math.random();
	
	// Get a rnadom number between 1 and 7
	num = num * (7 - 1) + 1;

	// Remove the decimal
	num = Math.floor(num);

	// Print the result
	document.getElementById('result').innerText = num;
}

You might have noticed these lines that start with a double forward slash throughout the tutorial. These are comments. the browse ignores these lines, but they are useful for leaving notes to yourself about what the code does.

Wrapping Up

In this tutorial, we built a simple app that simulates the rolling of a die. By building this simple app, we used functions, variables and constants. These ar just some of the fundamental concepts of programming .

There are many more things you can do with JavaScript. You can check that a form was filled our correctly, or build an entire social media app like Twitter or Facebook.

Leave a comment

Your email address will not be published. Required fields are marked *