How to Create a Riddle Generator with HTML, CSS, and JavaScript | Tutorial

Faraz

By Faraz -

Learn how to build a riddle generator using HTML, CSS, and JavaScript with this step-by-step tutorial. Follow our tutorial for easy implementation and customization.


Create a Riddle Generator with HTML, CSS, and JavaScript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Riddle generators are a delightful addition to websites, adding an interactive element that captivates users of all ages. In this tutorial, we'll walk you through the process of creating your very own riddle generator using HTML, CSS, and JavaScript. Whether you're looking to entertain visitors or enhance educational platforms, this step-by-step guide will equip you with the skills to craft an engaging experience that leaves a lasting impression. Let's dive in and unlock the mystery of building your own riddle generator!

Source Code

Step 1 (HTML Code):

Start by creating the basic HTML structure for your riddle generator. Define the necessary elements such as buttons and containers to display the riddles.

Let's break down the HTML code step by step:

1. <!DOCTYPE html>: This declaration specifies the document type and version of HTML being used, in this case, HTML5.

2. <html lang="en">: This is the root element of the HTML document. The lang attribute specifies the language of the document, which is English in this case.

3. <head>: This section contains meta-information about the document, such as the title, character encoding, viewport settings, and links to external resources like stylesheets and scripts.

  • <meta charset="UTF-8">: Specifies the character encoding for the document as UTF-8, which supports a wide range of characters.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport properties for responsive design, ensuring the webpage displays properly on different devices and screen sizes.
  • <title>Riddle Generator</title>: Sets the title of the webpage that appears in the browser tab.
  • <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">: Links to an external stylesheet hosted on Google Fonts, providing the font styles for the webpage.
  • <link rel="stylesheet" href="styles.css">: Links to an external stylesheet named "styles.css" located in the same directory as the HTML file.

4. <body>: This section contains the visible content of the webpage.

5. <div class="container">: A container div that holds the main content of the webpage.

  • <h1>Riddle Generator</h1>: Displays the main heading of the webpage.
  • <div class="riddle">: A div that contains the riddle and related elements.
  • <p id="riddle-text">What has keys but can't open locks?</p>: Displays the riddle text.
  • <button id="generate-btn" class="button">Generate Riddle</button>: A button that triggers the generation of a new riddle.
  • <button id="answer-btn" class="button hidden">Show Answer</button>: A button that reveals the answer to the riddle.
  • <p id="answer" class="hidden">Answer: A piano</p>: Displays the answer to the riddle, initially hidden.

6. <script src="script.js"></script>: Links to an external JavaScript file named "script.js" located in the same directory as the HTML file. This script contains functionality for generating riddles and toggling the visibility of the answer.

Step 2 (CSS Code):

Use CSS to style the HTML elements and make your riddle generator visually appealing.

Let's break down the CSS code step by step:

1. body: Styles for the body of the webpage.

  • font-family: Specifies the font for the body text as 'Poppins', a sans-serif font.
  • margin and padding: Set to 0 to remove any default margin and padding.
  • display: Set to flex to allow a flexible layout.
  • justify-content and align-items: Center the content horizontally and vertically within the body.
  • height: Set to 100vh, which means 100% of the viewport height, ensuring the content fills the entire viewport height.
  • background-color: Sets the background color of the body to #f0f0f0 (light gray).

2. .container: Styles for a container element.

  • text-align: Center the text within the container.

3. h1: Styles for the main heading.

  • color: Set the text color to #333 (dark gray).

4. .riddle: Styles for the riddle container.

  • background-color: Sets the background color to white.
  • padding: Adds 20 pixels of padding inside the container.
  • max-width: Sets the maximum width of the container to 600 pixels.
  • border-radius: Rounds the corners of the container with a radius of 10 pixels.
  • box-shadow: Adds a subtle shadow effect to the container.
  • animation: Applies the fadeIn animation to the container, making it fade in gradually over 0.5 seconds.

5. @keyframes fadeIn: Defines the fadeIn animation.

  • from: Initial state with opacity set to 0 and translateY to -20 pixels (moves the element up).
  • to: Final state with opacity set to 1 and translateY to 0 (normal position).

6. #riddle-text: Styles for the riddle text.

  • font-size: Sets the font size to 20 pixels.
  • margin-bottom: Adds 20 pixels of margin at the bottom of the text.

7. #answer: Styles for the answer text.

  • font-size: Sets the font size to 16 pixels.
  • margin-top: Adds 10 pixels of margin at the top of the text.
  • color: Sets the text color to blue.

8. .hidden: Styles for hiding elements.

  • display: Sets display to none, hiding the element.

9. .button: Styles for buttons.

  • background-color: Sets the background color to #4caf50 (green).
  • border: Removes the border.
  • color: Sets the text color to white.
  • padding: Adds 10 pixels of padding vertically and 20 pixels horizontally.
  • text-align: Centers the text within the button.
  • text-decoration: Removes underlining of text.
  • display: Sets to inline-block to allow other elements to sit beside it.
  • font-size: Sets the font size to 16 pixels.
  • cursor: Changes the cursor to a pointer on hover.
  • border-radius: Rounds the corners of the button with a radius of 5 pixels.
  • transition: Adds a smooth transition effect to the background color change.
  • margin-right: Adds 10 pixels of margin to the right side of the button.
  • animation: Applies the slideIn animation to the button, making it slide in from the top over 0.5 seconds.

10. @keyframes slideIn: Defines the slideIn animation, similar to the fadeIn animation.

11. .button:hover: Styles for button hover state.

  • background-color: Changes the background color to #45a049 (a slightly darker green) on hover.

12. .button:active: Styles for the button when clicked.

  • transform: Moves the button down by 3 pixels when clicked, giving it a pressed effect.
body {
  font-family: 'Poppins', sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.container {
  text-align: center;
}

h1 {
  color: #333;
}

.riddle {
  background-color: #fff;
  padding: 20px;
  max-width: 600px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

#riddle-text {
  font-size: 20px;
  margin-bottom: 20px;
}

#answer {
  font-size: 16px;
  margin-top: 10px;
  color: Blue;
}

.hidden {
  display: none;
}

.button {
  font-family: 'Poppins', sans-serif;
  background-color: #4caf50;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s ease;
  margin-right: 10px;
  animation: slideIn 0.5s ease-in-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.button:hover {
  background-color: #45a049;
}

.button:active {
  transform: translateY(3px);
} 

Step 3 (JavaScript Code):

Add JavaScript functionality to your riddle generator to generate random riddles each time the user clicks a button. Use arrays or objects to store the riddles and select them randomly.

Let's break down the JavaScript code step by step:

1. Riddles Data:

  • There's an array called riddles containing objects. Each object represents a riddle with a question and its corresponding answer.

2. Functions:

  • generateRiddle: This function is responsible for randomly selecting a riddle from the riddles array and displaying it along with a button to reveal the answer. It first generates a random index within the range of the riddles array, then retrieves the question and answer from the randomly selected riddle object and displays them on the webpage. It also hides the answer initially by adding a 'hidden' class to the answer element.
  • toggleAnswer: This function toggles the visibility of the answer. It targets the answer element on the webpage and toggles the 'hidden' class to either show or hide the answer.

3. Event Listeners:

  • The code sets up event listeners for two buttons:
  • generate-btn: This button triggers the generateRiddle function when clicked, generating a new riddle.
  • answer-btn: This button triggers the toggleAnswer function when clicked, revealing or hiding the answer to the current riddle.

4. Initialization:

  • Finally, the code calls generateRiddle function once initially to display a riddle when the page loads.
const riddles = [
  { question: "What has keys but can't open locks?", answer: "A piano" },
  { question: "I'm tall when I'm young, and I'm short when I'm old. What am I?", answer: "A candle" },
  { question: "What gets wetter as it dries?", answer: "A towel" },
  { question: "What has a head, a tail, is brown, and has no legs?", answer: "A penny" },
  { question: "The more you take, the more you leave behind. What am I?", answer: "Footsteps" },
  { question: "What can travel around the world while staying in a corner?", answer: "A stamp" },
  { question: "What has a neck but no head?", answer: "A bottle" },
  { question: "What comes once in a minute, twice in a moment, but never in a thousand years?", answer: "The letter 'm'" },
  { question: "What has cities but no houses, forests but no trees, and rivers but no water?", answer: "A map" },
  { question: "What belongs to you, but other people use it more than you?", answer: "Your name" },
  { question: "What is full of holes but still holds water?", answer: "A sponge" },
  { question: "What has a heart that doesn't beat?", answer: "An artichoke" },
  { question: "What can you catch but not throw?", answer: "A cold" },
  { question: "What has keys but can't open locks?", answer: "A keyboard" },
  { question: "What can you break, even if you never pick it up or touch it?", answer: "A promise" },
  { question: "What has a head, a tail, is brown, and has no legs?", answer: "A coin" },
  { question: "What is always in front of you but can't be seen?", answer: "The future" }
];

const generateRiddle = () => {
  const randomIndex = Math.floor(Math.random() * riddles.length);
  const riddleElement = document.getElementById('riddle-text');
  const answerElement = document.getElementById('answer');
  const answerBtn = document.getElementById('answer-btn');
  
  riddleElement.textContent = riddles[randomIndex].question;
  answerElement.textContent = `Answer: ${riddles[randomIndex].answer}`;
  answerElement.classList.add('hidden');
  answerBtn.classList.remove('hidden');
};

const toggleAnswer = () => {
  const answerElement = document.getElementById('answer');
  answerElement.classList.toggle('hidden');
};

document.getElementById('generate-btn').addEventListener('click', generateRiddle);
document.getElementById('answer-btn').addEventListener('click', toggleAnswer);

// Initial riddle generation
generateRiddle();

Final Output:

Create a Riddle Generator with HTML, CSS, and JavaScript.gif

See the Pen Untitled by Faraz (@codewithfaraz) on CodePen.

Conclusion:

Congratulations on completing this tutorial on creating a riddle generator using HTML, CSS, and JavaScript! By now, you've gained valuable insights into web development and learned how to engage your audience with interactive content.

Remember, the possibilities with your riddle generator are endless. You can customize it further, add more riddles, or even integrate it into games or quizzes. The key is to unleash your creativity and tailor it to suit your website's theme and audience.

We hope you've enjoyed this journey into the world of web development. Keep exploring, experimenting, and building amazing experiences for your users. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post