The Magic 8 Ball is a well known toy used for seeking advice. It has been developed in the 1950s by Mattel. The principle is quite easy. The user asks a yes-or-no question to the Magic 8 Ball which is a large plastic ball. Then, the user turns the Magic 8 Ball over to reveal a written answer which appears on the surface.

In that tutorial, you are going to discover how to create your own Magic 8 Ball in HTML5 with JavaScript. You can also watch this tutorial in video on YouTube :

Creating the structure of the page

The first step is to create the structure of the page for our Magic 8 Ball:

We define a content div for centering our Magic 8 Ball on the screen. Then, we define the title of our page in a h1 tag. We display a message to the user explaining how to play to the Magic 8 Ball. Next step is to define an input letting the user entering a question to ask to the Magic 8 Ball.

For displaying the Magic 8 Ball, we need to embed two divs. First div will be used to display the background of the Magic 8 Ball. Second div will be used to display the inside of the Magic 8 Ball. Besides, we define a first paragraph in the nested div to display the 8 number before the user clicks on the Magic 8 Ball to get his answer. Finally, we define a second paragraph which will be used to display the answers given by our Magic 8 Ball.

Displaying the Magic 8 Ball

Given our HTML5 structure, we need to define some CSS to display correctly our Magic 8 Ball:

Nothing unusual with this code. Just some classic CSS that allows us to have the following rendering for our Magic 8 Ball:

Adding the logic to the Magic 8 Ball with some JavaScript

Now, we need to add the logic to our Magic 8 Ball with some JavaScript. First step is to define a variable with the 20 answers of the Magic 8 Ball :

We will use a simple answers array. When the window is loaded, we install a click listener on the eight-ball div. So, when the user will click on the Magic 8 Ball our function will be called.

In that function, we check if a question has been entered. If not, we display an alert to the user indicating that he must enter a question. If so, we remove the 8 text of the first paragraph in the answer div. Then, we get a random answer in our array of answers. Finally, we have just to display this answer in the second paragraph inside the answer div.

It gives us the following complete code:

Our Magic 8 Ball in Action!

Best part of the tutorial is there. We are going to test our Magic 8 Ball with a simple question:

“Is Java better than Kotlin?”

So, this is the answer of our Magic 8 Ball:

Like you can see, the answer is clear ;).