Skip to main content

In this tutorial you will learn how to build a simple fortune teller app using basic JavaScript, HTML, and CSS. Here is a working example of what we will be building (with a limited range of fortunes for now).

View the final example in a standalone webpage

To download the full source code just right click on the link above and select either ‘Save Link As…’ (if you are using Firefox or Chrome), or ‘Download Linked File’ (if you are using Safari).

What You Will Need

  1. This tutorial is designed for beginners however things will make more sense if you have at least a basic understanding of JavaScript, HTML, and CSS. If you haven’t already, please check out my tutorials:
    1. How to Code a Basic Webpage Using HTML
    2. How to Develop a Basic Webpage Using HTML and CSS
    3. Intro to JavaScript
  2. You will need a code editor, such as Atom, Brackets or Visual Studio Code.
  3. For this tutorial I will also be using the Google Chrome browser however you should be able to follow along using other browsers such as Firefox or Safari if you prefer.

Table of Contents

  1. What is an Array?
  2. How to Create an Array Using JavaScript
  3. How to Get a Random Item from an Array Using JavaScript
  4. What is a Function?
  5. Create a Simple Function using Javscript
  6. Create the Fortune Teller HTML
  7. Add the Code to Update the HTML
  8. Add Some Style Using CSS
  9. Adding Animation
  10. Next Steps

What is an Array?

An array is a set of objects. In JavaScript arrays are used to store multiple values in a single variable. Arrays are very useful for working with sets of values.

You can find more information about arrays on w3Schools.

How to Create an Array Using JavaScript

In your code editor create a new HTML document called fortune-teller.html (or similar) and save it to an appropriate place on your computer.

The following example creates a variable called ‘fortunesArray’ and adds a simple array of values to it. The values of the array are put between opening and closing square brackets, eg […].

Note that each value in the array is separated by a comma (and there is no comma after the last item). Also note that in this case the values are strings so they are enclosed in speech marks.

<!DOCTYPE html>
<html>
<head>
<title>Fortune Teller</title>
</head>
    <body>

        <script>

            // Create array
            var fortunesArray = [
                "An exciting opportunity lies ahead",
                "A long time friend will bring wise advice in the coming week",
                "You will find great fortunes in unexpected places" 
           ];

        </script>
    </body>
</html>

* At some point you should come back and add your own items to the array. With only a few items in the array there is a good chance that the same fortune will be returned, so the more the better! 🙂

How to Get a Random Item from an Array Using JavaScript

To get a random item from the array using JavaScript add the following code to the JavaScript.

<script>

    // Create array
    var fortunesArray = [
        "An exciting opportunity lies ahead",
        "A long time friend will bring wise advice in the coming week",
        "You will find great fortunes in unexpected places" 
    ];

    // Get random item from array
    var randomFortune = fortunesArray[ 
        Math.floor(Math.random()*fortunesArray.length)
    ];

    // Log random item to the console 
    console.log(randomFortune);

</script>

This code declares a new variable called ‘randomFortune’ that is equal to the value of a random item from our fortunes array. It also logs the value of randomFortune to the console so we can check that it is working. I won’t go into detail about how random works in Javascript now, but just in case you’re interested here is a link to a page on w3Schools about JavaScript Random.

So if you haven’t already, save your code, refresh your page in the browser and check the browser console. You should see the random fortune displayed in the console.

* If by chance things aren’t working the console will also identify errors.

What is a Function?

A function is self contained section of code that runs a specific task. Typically functions are designed to be run multiple times. Functions can be called to run when an application loads, or from a user input, or from another function, etc. For example you may be coding a computer game that includes a function for say losing health or adding a point to the score etc.

For an outline of JavaScript functions please review this page about functions on w3Schools.

As the page on w3Schools describes, a JavaScript function is defined with the ‘function’ keyword followed by a name, and then followed by parenthesis (). Functions can include parameters within the parenthesis, but for what we are doing here and to keep things simple we won’t be including any parameters with the function.

Create a Simple Function Using Javascript

So let’s create a simple function that will generate a random item from our array and put it into an HTML page. We will call this function from a button click (user input).

The code for our function will look like this:

<script>

    // Create array
    var fortunesArray = [
        "An exciting opportunity lies ahead",
        "A long time friend will bring wise advice in the coming week",
        "You will find great fortunes in unexpected places" 
    ];

    function getFortune() {

        // Get random item from array
        var randomFortune = fortunesArray[ 
            Math.floor(Math.random()*fortunesArray.length)
        ];

        // Log random item to the console 
        console.log(randomFortune);
    }

</script>

Create the Fortune Teller HTML

Now we will add some simple HTML for the fortune teller app. We will put this immediately after the opening body tag, above the JavaScript script tag.

<body>

    <h1 id="fortune-holder">
        What is your fortune?
    </h1>

    <button onclick="getFortune()">
        Get Fortune
    </button>

    <script>
        //...    

* Note how the button calls the getFortune function when clicked.

Add the Code to Update the HTML

And last but not least, in the JavaScript we need to create a variable for the HTML element that will hold the fortune and user innerHTML to put the fortune in it. So our entire section of JavaScript should look like this:

function getFortune() {

    // Get random item from array
    var randomFortune = fortunesArray[ Math.floor(
        Math.random()*fortunesArray.length )
    ];

    // Log random item to the console 
    console.log(randomFortune);

    // Create a variable for the fortune-holder element in the html
    var fortuneHolder = document.getElementById("fortune-holder");

    // Put the randomFortune value into the fortune-holder element
    fortuneHolder.innerHTML = randomFortune;

}

Add Some Style Using CSS

So the app code should now work, at least in a basic sense. From here the design of the app could be greatly improved with some styling using CSS etc, and of course some additional fortunes added to the array.

I am aiming to create some CSS tutorials shortly, otherwise here is an example of some simple styles you could add to jazz the design up a bit. In this example I have included the CSS between style tags, within the head section of the HTML.

<head>
    <title>Fortune Teller</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>

        body {
            background-color: #000;
            color: #fff;
            text-align: center;    
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 100%;
            min-height: 100%;
            position: absolute;
        }

        h1 {
            width: 82%;
            max-width: 600px;
            font-weight: normal;
            font-size: 42px;
        }

        button {
            font-size: 18px;
            padding: 15px 20px;
            margin-top: 40px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            box-shadow: 2px 2px 12px rgba(0,0,0,.2);
            transition: transform .3s;
        }

        button:hover {
            transform: scale(1.125);
        }

    </style>

</head>

* Please note, I have also included a meta viewport tag in the head. This is a must have if you want to view your page on a mobile. For more information see this page about the Viewport tag on w3Schools.

Adding Animation

If you run the app now notice how if by chance you get the same fortune there is no change in the website content. I think this is bad interface design in that it may confuse the user. – Without any obvious feedback the user may think that the interface is not working. My feeling is that an interface needs to always respond to the user’s input. So this is relatively advanced CSS and Javascript but if you add the following code you will get a nice transition on the fortune holder element.

Firstly add this to the CSS:

@keyframes fade {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

.fade-animation {
    animation: fade .5s;
}

Here the @keyframes defines the animation which will transition the opacity from 0 to 1.

Now add the class to the fortune-holder element in the HTML.

<h1 id="fortune-holder" class="fade-animation">
    What is your fortune?
</h1>

Now the tricky part. If you run the app now, the transition will only happen when the page is first loaded. Unfortunately there is currently no straight forward way within the CSS to trigger the animation to run again. There are many ways you could handle this, but here I will use this trick courtesy of CSStools, by adding the following to the JavaScript.

* Make sure you put this code within the getFortune function:

// Remove animation class (if it has it)
fortuneHolder.classList.remove("fade-animation");

// Trigger the element to be redrawn
void fortuneHolder.offsetWidth;

// Re-add the animation class
fortuneHolder.classList.add("fade-animation");

Next Steps

From here you may want to learn how to convert a document like your fortune teller app into a fully fledged progressive web app or ‘PWA’ for short. This will make it installable and allow it to work offline. I am planning to create a tutorial series that will show you how to build progressive web apps shortly.

I am also planning to create some more tutorials that will build up your JavaScript skills through making some more simple JavaScript apps.


Otherwise I hope this tutorial was useful for you. I’m planning to include the next tutorials in this series shortly as well as a video demonstration to go along with this tutorial. Please don’t hesitate to get in touch via email at contact@henryegloff.com if anything is unclear.


If you would like to stay in the loop when I publish new tutorials you might want to consider subscribing to my Youtube Channel, or if you use RSS you can find feeds available for any or all of my tutorial categories.

I would love to make it my thing to create high quality tutorials that are 100% free with no strings attached.

If this tutorial was useful for you please consider showing your appreciation and offering your support. It will make my day!

Buy me a coffee

Filed under:
Coding, Web Development

Similar Tutorials:

Intro to JavaScript

Intro to JavaScript

A basic introduction to coding with JavaScript, with simple explanations and code examples to follow along with.

All Tutorials

Henry Egloff
Twitter Twitter 2 Facebook Linked In Instagram Codepen Behance Youtube Opensea Heart