Creating a Trivia Game with AJAX-Loaded Questions
Table of Contents
- Introduction
- Setting Up the Project
- Creating the HTML Structure
- Styling the Game with CSS
- Implementing AJAX to Load Questions
- Handling User Input and Displaying Answers
- Keeping Track of Score and Progress
- Adding a Timer for Each Question
- Enhancing the Game with Animations
- Optimizing Performance and Debugging
- Deploying the Game
- Conclusion
1. Introduction
A trivia game is an interactive quiz where players answer questions on various topics. In this guide, we’ll build a trivia game using AJAX to dynamically load questions from an external API or JSON file. The game will include features like score tracking, a timer, and smooth animations.
2. Setting Up the Project
To get started, create the following files:
index.html
style.css
script.js
We’ll also use jQuery for AJAX requests, so include it in the HTML file:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
3. Creating the HTML Structure
<div class="game-container">
<h1>Trivia Game</h1>
<p id="question"></p>
<div id="options"></div>
<p>Score: <span id="score">0</span></p>
<p>Time Left: <span id="timer">10</span> seconds</p>
<button id="next">Next Question</button>
</div>
4. Styling the Game with CSS
.game-container {
text-align: center;
font-family: Arial, sans-serif;
}
#options button {
display: block;
margin: 5px auto;
padding: 10px;
width: 200px;
cursor: pointer;
}
5. Implementing AJAX to Load Questions
function loadQuestion() {
$.ajax({
url: "https://opentdb.com/api.php?amount=1&type=multiple",
method: "GET",
success: function (data) {
let questionData = data.results[0];
$("#question").text(questionData.question);
let answers = [...questionData.incorrect_answers, questionData.correct_answer];
answers.sort(() => Math.random() - 0.5);
$("#options").empty();
answers.forEach(answer => {
$("#options").append(`<button class='answer-btn'>${answer}</button>`);
});
}
});
}
$(document).ready(loadQuestion);
6. Handling User Input and Displaying Answers
$(document).on("click", ".answer-btn", function () {
let selected = $(this).text();
let correct = $("#question").data("correct-answer");
if (selected === correct) {
alert("Correct!");
score++;
} else {
alert("Wrong!");
}
$("#score").text(score);
});
7. Keeping Track of Score and Progress
let score = 0;
function updateScore() {
$("#score").text(score);
}
8. Adding a Timer for Each Question
let timeLeft = 10;
function startTimer() {
let timerInterval = setInterval(() => {
timeLeft--;
$("#timer").text(timeLeft);
if (timeLeft === 0) {
clearInterval(timerInterval);
alert("Time's up!");
loadQuestion();
}
}, 1000);
}
9. Enhancing the Game with Animations
- Add fade-in effects to questions.
- Highlight the correct answer after selection.
10. Optimizing Performance and Debugging
- Minimize AJAX requests using caching.
- Optimize DOM updates to reduce flickering.
11. Deploying the Game
- Upload files to GitHub Pages or Netlify.
- Ensure the API endpoint is accessible.
We successfully built a trivia game with AJAX-loaded questions, a scoring system, and a timer. Future improvements could include categories, difficulty levels, and leaderboards. Happy coding!