How I Built a Magic 8 Ball in JavaScript (No Backend, No Storage)
Disclosure: I run Ask8BallFree, a free online Magic 8 Ball. I built it as a small front-end project, and this post explains how it works.
The idea
A Magic 8 Ball is a good first JavaScript project because the whole interaction is simple: ask a yes-or-no question, shake the ball, and show one answer. There is no account, no database, and nothing to save.
The three pieces
- HTML — a question input, a button, and a place to show the answer.
- CSS — the round ball, the dark window in the middle, and a short shake animation.
- JavaScript — the list of answers and the random choice.
The answers
I kept the classic set of twenty answers, split into positive, uncertain, and negative ones:
const answers = [ "It is certain.", "Without a doubt.", "Yes, definitely.", "Most likely.", "Ask again later.", "Cannot predict now.", "Do not count on it.", "My sources say no." ]; That is only a sample — the full list follows the same pattern.
Picking one at random
The core of the project is three lines:
const randomIndex = Math.floor(Math.random() * answers.length); const answer = answers[randomIndex]; answerElement.textContent = answer; Math.random() gives a number from 0 up to (but not including) 1. Multiplying by the number of answers and rounding down with Math.floor() gives a valid index every time.
A small detail that matters
Before showing an answer, I check that the question is not empty. If it is, I ask the user to type a question first. I also clear the old answer while the ball is shaking, so the new one feels like a fresh result.
For the shake, I add a CSS class, wait about half a second, then remove the class and show the answer. No library is needed.
What I learned
The interesting part was not the random choice. It was keeping the project small: one page, plain JavaScript, no backend, and no storage. That made it easy to test, easy to share, and easy to keep free.
If you want a beginner project with a visible result in an evening, a Magic 8 Ball is a good choice. Start with the answers, add the random pick, and then make the ball look and feel fun.