Welcome to my latest tutorial, where you’ll learn how to build a magic eight ball with JavaScript.
I usually write tutorials for an audience of people who know at least a little bit of front-end programming. I’ve put more focus on the concepts and thought processes used in building the abstractions than on the technical details. One of my recent tutorials, a crossword puzzle generator, is a good example of what I’m talking about.
This post will be different. I’m going to show you how to build a magic eight ball with JavaScript, and the tutorial is designed for complete beginners.
You can check it out here.
And you can view the source code here. You can compare your code to mine if you run into troubles along the way.
My tutorials are fun because you get a working game at the end. I think there is a lot to be said for that. Most people don’t get into programming because they enjoy sorting lists or learning about data structures. They want to build something cool.
That being said, my tutorials usually require you to apply yourself and do more of your own research if you want to maximize the benefits to you. If you’re just blindly copying and pasting you won’t learn much.
True growth as a developer comes when you can combine structured learning of the fundamentals with building cool stuff.
The goal of this specific tutorial is to provide that kind of experience, with a little more focus on learning the fundamentals.
Technologies of the Web
We’ll be building this magic eight ball using front-end web technologies. Understanding these technologies is key to building a strong foundation as a web developer.
There are three fundamental technologies that every developer must know in order to write code that will run in a web browser: HTML, CSS, and JavaScript.
HTML
HTML stands for hypertext markup language. It is a domain specific programming language that allows you to display structured content in a web browser.
Notice how this page you’re reading has headings in larger font and breaks between paragraphs? That effect is due to HTML tags.
What are tags?
Tags are elements on the page that describe how content should be displayed. There are different tags for displaying headings, paragraphs, buttons, line breaks, images, and much more. If you want to be a web developer, HTML is the first thing you should learn. Fortunately, it’s pretty easy to pick up.
CSS
CSS stands for cascading style sheets. It is a programming language used for applying colors, fonts, positioning, borders, and much more to HTML elements. Basically, it makes the page look pretty.
It’s called cascading because of the way it determines which style to apply if more than one rule matches a particular element.
CSS can be included in the HTML directly, or pulled in from a separate file. It used to be considered poor form to have inline CSS, but that standard has changed a bit with some of the new front-end frameworks. For this tutorial, I’ll be including the CSS via a separate file.
JavaScript
Out of the three languages, JavaScript is probably the most challenging to learn (although advanced CSS can get pretty crazy). It’s also the most rewarding, as many of the same concepts will apply to other programming languages, like Java, Python, or C++.
JavaScript brings your page to life. It allows you to introduce dynamic behavior to the page. You can add functionality that is dependent upon the actions of the user. It’s where the bulk of the difficulty, and fun, of programming lies.
Like CSS, you can include JavaScript directly in the HTML. I’ll be including it via a separate file.
We’ll be displaying the answers from our magic eight ball with JavaScript.
Where To Write The Code
To start developing for the web, all you really need is a text editor program. I like Sublime, but there are many good ones to choose from. You can even use plain old Notepad, but I recommend downloading something better. Here is a good list to pick from:
- Sublime
- Visual Studio Code
- Notepad++
- Atom
Make Your Life Easier With a Debugger
In my opinion, it’s also worth familiarizing yourself with your browser’s developer tools. They are extremely helpful for experimenting, debugging issues, and seeing what’s going on in your code behind the scenes. For this tutorial I’ll be using Google Chrome.
In Chrome, you can bring up the developer tools by using the keyboard shortcut: Ctrl + Shift + I, or by right clicking on the page and selecting “Inspect”. Check out this post to familiarize yourself with the basics of how to use these tools.
Alternatively, you can wait and learn them when you need them.
Creating the HTML File
Ok, let’s get started making the magic eight ball.
Once you have downloaded a text editor you have all you need to begin. Pick any folder/directory on your computer as the location of your website. It can be a simple as creating a folder called “magic-eight-ball” on your Desktop. This is the location where you will be saving your HTML, CSS, and JavaScript files.
Next, open up a brand new file in your text editor of choice. This is where we are going to write the HTML code.
Begin by adding the following code to the file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
This is the basic structure of an HTML document. The words in angle brackets are called tags.
There are opening and closing tags. The tags that have a forward slash before the name are the closing tags. Although most HTML elements require both, there are many HTML elements that do not require a closing tag. We’ll see some examples of this in a moment.
The content you will be adding goes between the opening and closing tags. These tags are what create visible elements on the page.
The first element you see is the doctype. This is not an HTML tag, but information the browser needs to know what kind of document to display. In our case, the type of document is an HTML document. There are other doctypes, but that discussion is beyond the scope of this tutorial.
We have three tags so far: html, head, and body. The html tag signifies the beginning of the HTML document. Everything on the page goes inside it. The head tag contains meta information about the page and can also be used as a place to import other files. The body tag is where the bulk of our content will go.
Go ahead and save this file as index.html in the folder you previously created.
Now add some more code so your HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Magic Eight Ball</title>
<link rel="stylesheet" href="magic-eight-ball.css">
<link rel="shortcut icon"
href="https://mitchum.blog/wp-content/uploads/2019/05/favicon.png" />
</head>
<body>
<main>
<h3 class="heading">Magic Eight Ball</h3>
<h5 class="heading">
<a href="https://mitchum.blog/building-a-magic-eight-ball-with-javascript/">Tutorial</a> |
<a href="https://github.com/mmaynar1/games/tree/master/magic-eight-ball">Github</a> |
<a href="https://mitchum.blog/subscribe/">Subscribe</a>
</h5>
</main>
</body>
</html>
Let’s look at what we added. You should notice that the head and body tags have even more tags inside of them now.
Head Tag
We have added a title tag and two link tags. The title tag will be displayed in the tab of your browser.
The first link tag pulls in the CSS class which we have yet to create. We’ll do that in a moment.
The second link tag sets the favicon image. This is the little icon that shows up in the browser tab. We’re pulling the image from the web server that runs my blog.
Body Tag
We have added a main tag inside the body. This element contains the main content of the page. In our case, this is almost everything. On other websites, however, you might find items like common footers and navigation elements outside of the main tag.
Inside our main tag we have added two h tags. These are heading tags that display larger text meant to serve as headings for sections of content.
The first heading tag contains text representing the title of our page: Magic Eight Ball. It also contains a class property labeled “heading”. This is a CSS class. Later we will add style to it by adding code to our CSS file.
Adding Hyperlinks
The second heading tag, which is also assigned the “heading” class, contains hyperlinks to my blog and Github page.
You might know hyperlinks by their more common nickname: links. These hyperlinks are created by using “a”, or “anchor” tags. The href property specifies which url the hyperlink will direct the browser to. The text between the anchor tags specifies what the link name will be.
You should really click on that Subscribe link and submit the form. I’ve made it easy for you by adding my own link to it right here. 😉
At this point you should save your changes. Then, navigate to this file and open it in a browser. In the address bar you should be able to see the path to your file. On the page itself you should see the title and the links below it.
Finishing Up the HTML
Now it’s time to add the rest of the HTML content. See the new additions below:
<!DOCTYPE html>
<html>
<head>
<title>Magic Eight Ball</title>
<link rel="stylesheet" href="magic-eight-ball.css">
<link rel="shortcut icon"
href="https://mitchum.blog/wp-content/uploads/2019/05/favicon.png" />
</head>
<body>
<main>
<h3 class="heading">Magic Eight Ball</h3>
<h5 class="heading">
<a href="https://mitchum.blog/building-a-magic-eight-ball-with-javascript/">Tutorial</a> |
<a href="https://github.com/mmaynar1/games/tree/master/magic-eight-ball">Github</a> |
<a href="https://mitchum.blog/subscribe/">Subscribe</a>
</h5>
<br>
<div id="answerButton">
<button class="button" type="button" onclick="displayAnswer()">Shake It</button>
</div>
<br>
<div id="magicEightBall">
<div id="circle"></div>
<img src="magic-eight-ball.png"/>
</div>
<br>
</main>
<script src="magic-eight-ball.js"></script>
</body>
</html>
In this step we’ve added the bulk of the HTML needed to make our magic eight ball. We’ve added two div tags. People use div tags a lot. You can think of them as generic placeholders for content.
Adding the “Shake It” Button
The first div is given the id of “answerButton”. We’ll use this id for adding styling via CSS. Inside the div tag is a button child tag.
Child tags are tags inside of other tags. The outer tag is referred to as the parent tag. (Image description?)
This button is assigned the class “button”, the type “button”, and a JavaScript function to execute when somebody clicks it. We’ll write this function later when we get to the JavaScript file. The text on the button will say “Shake It”. When you click this button, you’ll get an answer from the magic eight ball.
The second div is given the id of “magicEightBall”. We’ll use this id for adding styling via CSS, but also for adding functionality in the JavaScript code.
Adding the Magic Eight Ball
There are two child tags in this div. The first is another div with the id of “circle”. The second is an img tag with a src attribute pointing to an image called “magic-eight-ball.png”. You’ll need to download this image from my server, give it the name “magic-eight-ball.png”, and save it in your working folder/directory along with your other files.
There are also br tags scattered throughout to provide spacing between different page elements. Go ahead and add those as well.
Finally, there is a script tag right outside the main closing tag. The src attribute points to magic-eight-ball.js, the JavaScript file we will be adding later.
If you save and open the HTML file now it will have all the content, but it will look pretty ugly:
We’re going to fix that by adding the CSS file, magic-eight-ball.css.
Creating the CSS File
Open up a brand new file in your text editor and save it in the same location as your index.html file under the filename, “magic-eight-ball.css”.
It’s important that the name matches the one you specified in the HTML file, otherwise the CSS file won’t be found. Add the following blocks of code one at a time, and save as you go. Observe how the page changes as you go.
Setting the Background Color
body {
background: cornflowerblue;
}
This block of code does one thing and one thing only. It sets the background color of the body HTML element to a nice blue color. If you save the file and refresh your browser you’ll notice the color change.
Centering the Page Contents
main {
max-width: 610px;
margin: auto;
}
After refreshing the page you should see everything centered on the page much more nicely. We have set the max width of the main element to 610px (px stands for pixels), and we have set the margin to auto, horizontally centering all of the content within it.
Applying Styles to Our HTML Elements
h3, h5, #answerButton, #magicEightBall {
text-align: center;
color: khaki;
margin: 5px;
}
This block of code is applying styles to four different HTML elements: all h3 tags, all h5 tags, the HTML element with the id of “answerButton”, and the HTML element with the id of “magicEightBall”.
By adding this code block we will apply three different styles to these elements. We’ll center the text within them, set their text color to khaki, and set the margin (the space around the element) to 5px.
Styling the Answer Display Circle
#circle {
font-size: 14pt;
background-color: white;
color: black;
position: absolute;
margin-left: 70px;
margin-top: 70px;
height: 150px;
width: 150px;
border-radius: 50%;
display: none;
}
There is a lot going on in this code block. We are applying many different styles to the HTML element with the id of circle, which represents the area where the answer will appear.
We are setting the font size to 14pt. This seemed reasonable after I did a little bit of testing. We are also setting the background to white and the text color to black so that the answer area will have good contrast and look good on top of the magic eight ball image.
We are using absolute positioning. This will cause the element to be positioned relative to the nearest position ancestor, which in our case is the HTML element with the id of “magicEightBall”. We are also adding left and top margins of 70px to help us begin centering the answer area in the middle of the magic eight ball.
We are setting the height and width of element to 150px, creating a square. Then we set the border radius to 50% which rounds the corners into a square.
Finally, we set the display to none, hiding it from view until the person shakes the magic eight ball.
Now the magic eight ball looks a lot better:
Creating the JavaScript File
Now it’s time for the fun part. We’re going to make our magic eight ball come to life with JavaScript.
Open up a brand new file in your text editor and save it in the same location as your index.html file under the filename, “magic-eight-ball.js”. It’s important that the name matches the one you specified in the HTML file, otherwise the JavaScript file won’t be found.
Creating the Answers Array
The first thing we’re going to do is create a list of possible answers the magic eight ball can respond with. We’ll refer to this list as an array. The term array is very common among different programming languages. Simply put, it is a structure for storing a sequential list of data in memory. In our case, the data will be the answers that the magic eight ball will give to us. Let’s define the array in our code:
let answers = [
'Seems unlikely.',
'Not a chance.',
'In your dreams.',
'Get real, kid.',
'Absolutely.',
'Maybe.',
'It is certain.',
'Ask me later.',
'Chances seem good.',
'I don\'t know, I\'m just a stupid piece of plastic.',
'Ask again later.',
'Signs point to yes.',
'No.',
'Yes.',
'Nope.',
'Don\'t count on it.',
'Is the Pope Catholic?',
'Does a one legged duck swim in a circle?'
]
We’ve used the let keyword to define a variable named answers. A variable is a name that refers to a piece of data.
We have set this answers variable (via the = sign) to hold an array of strings. For this tutorial, you can think of a string as a sequence of characters. We’ll be using strings to represent our answers.
A comma is used to separate each element of the array. By adding the code above we have defined a variable that holds an array containing 18 answers, each represented as a string.
Creating the displayAnswer Function
Now let’s add the JavaScript function to display the answers when the player clicks the “Shake It” button.
let displayAnswer = function()
{
let index = Math.floor(Math.random() * answers.length);
let answer = answers[index];
let element = document.getElementById( 'circle' );
element.style.display = 'inline-block';
element.innerHTML = '<br><br>' + answer;
}
We’ve defined another variable, but this time we have pointed it to a function instead of an array. You can think of a function as a container for code that can be reused. You can run the code inside by “calling” that function.
If you search through the index.html file we created and look for displayAnswer() you’ll see where this function is called from. Whenever we click the “Shake It” button, this function will be called.
Functions are very useful to us as programmers. We can use them for organizational purposes and to prevent us from writing the same code over and over again.
Inside our displayAnswer function is code that will show a random answer on the magic eight ball. Let’s break down each line.
Getting a Random Index
let index = Math.floor(Math.random() * answers.length);
The first thing we do is get a random index. This random index will correspond to one of the elements in our answers array. Each element in the array is assigned an index, starting with 0. So the array above looks like this:
We generate this random index by using a few functions provided by JavaScript’s built in Math object. We multiply the length of the answers array by a random number between 0 (inclusive) and 1 (exclusive). Then, we round it down to the nearest integer.
Picking a Random Answer
let answer = answers[index];
Once we have our random index we need to retrieve the corresponding answer from the array. We do this by declaring a new variable and setting it to a value in the array corresponding to that index.
Finding the Circle
let element = document.getElementById( 'circle' );
Once we have our answer we need to display it on the page inside the magic eight ball. The first step is finding the HTML element. We use the above line of code to grab the element with the id of “circle”. In this case “document” refers to our web page. We save off a reference to it in a variable named “element”.
Displaying the Circle
element.style.display = 'inline-block';
Now that we have the element we need to make it visible. Remember, in our CSS file we previously hid this element from view. We will change its display from “none” to “inline-block”.
Showing the Answer
element.innerHTML = '<br><br>' + answer;
Finally, we need to populate the element with the answer. We’ll create a string of two br tags, to help center the answer in the middle of the circle, and then append the answer to it. The plus symbol can be used for doing math, but in the case of strings it will concatenate them together.
Now save your file and check out the game you’ve created! You should get a random answer every time you click the “Shake It” button.
Congrats, you have created a magic eight ball with JavaScript!
I hope you learned something from this tutorial, especially if you are brand new to programming. We have barely begun scratching the surface on what we can accomplish with these programming languages. The whole web is built using these technologies, and there are many more elements we can create, styles we can apply, functions we can write. There is boundless room for creativity.
If you’d like to keep learning more, check out some of my other game tutorials.
You can also follow me on Twitter and subscribe to this blog to stay up to date with what I’m up to.