From a06825c7e116d5d993168b9272bc59c60a621480 Mon Sep 17 00:00:00 2001 From: Yashwanth Varma Date: Wed, 11 Oct 2023 08:23:38 +0530 Subject: [PATCH] Quiz App using pure html,css,javascript --- .../brickBreaker.code-workspace | 11 + QuizApp/yashwanthvarma18/index.html | 107 +++++++ QuizApp/yashwanthvarma18/index.js | 275 ++++++++++++++++++ QuizApp/yashwanthvarma18/style.css | 168 +++++++++++ 4 files changed, 561 insertions(+) create mode 100644 QuizApp/yashwanthvarma18/brickBreaker.code-workspace create mode 100644 QuizApp/yashwanthvarma18/index.html create mode 100644 QuizApp/yashwanthvarma18/index.js create mode 100644 QuizApp/yashwanthvarma18/style.css diff --git a/QuizApp/yashwanthvarma18/brickBreaker.code-workspace b/QuizApp/yashwanthvarma18/brickBreaker.code-workspace new file mode 100644 index 000000000..e9793da78 --- /dev/null +++ b/QuizApp/yashwanthvarma18/brickBreaker.code-workspace @@ -0,0 +1,11 @@ +{ + "folders": [ + { + "path": "../brickBreaker" + }, + { + "path": "." + } + ], + "settings": {} +} \ No newline at end of file diff --git a/QuizApp/yashwanthvarma18/index.html b/QuizApp/yashwanthvarma18/index.html new file mode 100644 index 000000000..310af9585 --- /dev/null +++ b/QuizApp/yashwanthvarma18/index.html @@ -0,0 +1,107 @@ + + + + + + + Quiz + + + + + + + + +
+ + +
+ +

Random Quiz

+ +
    + +
  • Correct: 0
  • + +
  • Incorrect: 0
  • +
+
+ + +
+ +
+
+ +
+ Try It Out + Test your knowledge with a random quiz! +
+ + +
+ + + +
+ + + +
+ + + +
+ + + +
+
+
+ + + + + +
+ + + diff --git a/QuizApp/yashwanthvarma18/index.js b/QuizApp/yashwanthvarma18/index.js new file mode 100644 index 000000000..393115031 --- /dev/null +++ b/QuizApp/yashwanthvarma18/index.js @@ -0,0 +1,275 @@ +// All global variables +let STORE = []; // Array to store quiz questions and answers +let questionNumber = 1; // Current question number +let correctAnswers = 0; // Number of correct answers +let incorrectAnswers = 0; // Number of incorrect answers +let currentQuestion = 0; // Index of the current question +let correctMessage; // Message to display for correct answers +let incorrectMessage; // Message to display for incorrect answers + +// Runs when the window is loaded +window.onload = function() { + buttons(); // Attach event handlers to buttons + $('.scoreboard').html(scores()); // Initialize the scoreboard +}; + +// All of the button press options +function buttons() { + // Event handler for the "Begin" button + $('.box').on('click', '#begin', function() { + event.preventDefault(); // Prevent page reload + let numQ = $('#numQ').val(); // Get the number of questions from the input + let diff; + let cat; + + // Check if difficulty is specified and construct URL + if ($('#difficulty').val() === 'any') { + diff = ''; + } else { + diff = `&difficulty=${$('#difficulty').val()}`; + } + + // Check if category is specified and construct URL + if ($('#category').val() === 'any') { + cat = ''; + } else { + cat = `&category=${$('#category').val()}`; + } + + // Display loading message and prevent multiple clicks + $('#begin').replaceWith(`

Loading...

`); + createQuestions(numQ, diff, cat); + }); + + // Event handler for the "Next" button + $('.box').on('click', '#next', function() { + event.preventDefault(); + handleNext(); + }); + + // Event handler for the "Submit" button (when guessing) + $('.box').on('click', '#guess', function() { + event.preventDefault(); + handleGuess(); + }); + + // Event handler for the "New Quiz" button (restart) + $('.box').on('click', '#restart', function() { + event.preventDefault(); + STORE = []; // Clear questions before starting a new game + restartQuiz(); + }); +} + +// Uses fetch to utilize the API and sends the JSON data to the testData function +function createQuestions(numQ, diff, cat) { + let url = `https://opentdb.com/api.php?amount=${numQ}&type=multiple${diff}${cat}`; + fetch(url) + .then((response) => response.json()) + .then((responseJson) => testData(responseJson, numQ, diff, cat)) + .catch((error) => alert(error)); +} + +// This makes sure the API has enough questions for requested specifications +function testData(data, numQ, diff, cat) { + if (data.response_code === 0) { + createArr(data); // If enough questions are available, create an array of questions + } else { + numQ--; + createQuestions(numQ, diff, cat); // Try again with fewer questions + } +} + +// creates the array of questions using the JSON data +function createArr(data) { + for (let question in data.results) { + let arr = []; + + // Create an array of potential answers + arr.push(data.results[question].correct_answer); + arr.push(data.results[question].incorrect_answers[0]); + arr.push(data.results[question].incorrect_answers[1]); + arr.push(data.results[question].incorrect_answers[2]); + + // Shuffle the order of the answers + for (let i = arr.length - 1; i > 0; i--) { + let j = Math.floor(Math.random() * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + + // Create an object containing the question, array of potential answers, and actual answer + let newObj = { + question: data.results[question].question, + answers: arr, + rightAnswer: data.results[question].correct_answer + }; + STORE.push(newObj); + } + renderQuestion(); // Display the first question +} + +// Renders the question form +function renderQuestion() { + $('.box').html( + ` +
+
+ Question ${questionNumber} of ${STORE.length} + ${STORE[currentQuestion].question} +
+
+ Answers + ${STORE[currentQuestion] + .answers[0]}
+ ${STORE[currentQuestion] + .answers[1]}
+ ${STORE[currentQuestion] + .answers[2]}
+ ${STORE[currentQuestion] + .answers[3]}
+ + +
+
+ + + ` + ); +} + +// Handles when someone guesses an answer +function handleGuess() { + // Checks to see if an option is checked + if ($("input[name='answer']:checked").data('value')) { + guess(); + } else { + // Shows the error message if nothing is checked + if ($('#error').hasClass('hidden')) { + $('#error').toggleClass('hidden'); + } + } +} + +// Checks whether answer is correct or not +function guess() { + if (!$('#error').hasClass('hidden')) { + $('#error').toggleClass('hidden'); + } + + // Disables ability to guess again on the current question + $('input[type=radio]').attr('disabled', true); + + // Handle special characters in answers + let encodedStr = STORE[currentQuestion].rightAnswer; + let parser = new DOMParser(); + let dom = parser.parseFromString('' + encodedStr, 'text/html'); + let decodedString = dom.body.textContent; + + correctMessage = `That is correct! Way to go!`; + incorrectMessage = `That is incorrect. The correct answer is: ${decodedString}.`; + + if ($("input[name='answer']:checked").data('value') == decodedString) { + $('#message').text(`${correctMessage}`); + correctAnswers++; + } else { + $('#message').text(`${incorrectMessage}`); + incorrectAnswers++; + } + toggleClasses(); // Toggle messages for correct/incorrect and update the score +} + +// Toggles the messages for correct/incorrect and shows the new score +function toggleClasses() { + $('#message').toggleClass('hidden'); + $('#guess').toggleClass('hidden'); + $('#next').toggleClass('hidden'); + $('.scoreboard').html(scores()); // Update the scoreboard +} + +// Handles when someone presses the next button +function handleNext() { + if (questionNumber != STORE.length) { + currentQuestion++; + questionNumber++; + renderQuestion(); // Display the next question + } else { + $('.box').html(results()); // Display the results when all questions are answered + } +} + +// This is the display for the results page. +function results() { + // Messages given based on the score + let goodScore = ' You really know your trivia!'; + let okayScore = ' Try again and see if you can do better!'; + let badScore = ' Better Luck Next Time.'; + + let scoreMessage; + + if (correctAnswers > STORE.length * 0.7) { + scoreMessage = ' 😎👌' + goodScore; + } else if (correctAnswers > STORE.length * 0.4) { + scoreMessage = ' 😉' + okayScore; + } else { + scoreMessage = ' 😵' + badScore; + } + + const resultBox = ` +
+

Results

+

+ You got ${correctAnswers} out of ${STORE.length} questions correct. ${scoreMessage} +

+ +
+ `; + return resultBox; +} + +// Resets everything and starts fresh +function restartQuiz() { + questionNumber = 1; + correctAnswers = 0; + incorrectAnswers = 0; + currentQuestion = 0; + $('.box').html(` +
+
+ Try It Out + Test your knowledge with a random quiz! +
+
+ + +
+ + +
+ + +
+ +
+ `); + $('.scoreboard').html(scores()); // Update the scoreboard +} + +// Handles the display of the scores +function scores() { + const scoreMake = ` +
  • ✅ Correct: ${correctAnswers}
  • +
  • ❌ Incorrect: ${incorrectAnswers}
  • + `; + return scoreMake; +} diff --git a/QuizApp/yashwanthvarma18/style.css b/QuizApp/yashwanthvarma18/style.css new file mode 100644 index 000000000..a0252bb59 --- /dev/null +++ b/QuizApp/yashwanthvarma18/style.css @@ -0,0 +1,168 @@ +/* Set the background image for the entire body and reset margins */ +body { + background-image: url('https://i.imgur.com/ZA491RE.png'); + margin: 0; + } + + /* Style for the main content container */ + .whole { + background-image: linear-gradient(to bottom, #ff6f61, #fdbb2d); + background-image: linear-gradient(to bottom, #6a0572, #5ceac9); + height: 800px; + width: 100%; + } + + /* Style for the header section */ + header { + background-color: #191970; + background-image: url('https://i.imgur.com/Cze1FW4.png'); + border-bottom: 2px solid black; + color: #FFFFFF; + display: flex; + justify-content: space-evenly; + /* padding: 10px; */ + width: 100%; + } + + /* Style for the main title */ + h1 { + margin-top: 15px; + } + + /* Common style for h2 and legend */ + h2, + legend { + font-family: 'Bangers', cursive; + font-weight: 700; + letter-spacing: 0.1em; + } + + /* Style for secondary titles */ + h2 { + font-size: 30px; + } + + /* Style for legends */ + legend { + font-size: 25px; + } + + /* Style for buttons */ + button { + background-color: #FFFFFF; + border: 2px solid #0099cc; + border-radius: 6px; + font-size: 18px; + margin-top: 15px; + padding: 5px; + } + + /* Hover effect for buttons */ + button:hover { + background-color: #0099cc; + } + + /* Common style for fieldset, message, list items, and results */ + fieldset, + #message, + li, + .results { + font-size: 18px; + font-family: 'Oxygen', sans-serif; + margin: 5px; + } + + /* Style for images */ + img { + border: 2px solid #FFFFFF; + border-radius: 50%; + display: block; + margin-left: auto; + margin-right: auto; + } + + /* Style for lists */ + ul { + list-style-type: none; + margin-right: 15px; + } + + /* Style for list items */ + li { + display: inline-block; + } + + /* Style for a specific container */ + .box { + background-color: #D3D3D3; + border: 2px solid black; + border-radius: 5px; + margin: 0 auto; + margin-top: 100px; + padding: 20px; + width: 50%; + } + + /* Style for feedback text */ + .feedback { + font-weight: 700; + } + + /* Style for result text */ + .results { + text-align: center; + } + + /* Hide elements with the "hidden" class */ + .hidden { + display: none; + } + + /* Style for correct answers */ + .right { + color: #008000; + } + + /* Style for wrong answers */ + .wrong { + color: #FF0000; + } + + /* Media Query for small screens (max-width: 430px) */ + @media screen and (max-width: 430px) { + /* Adjust image height */ + img { + height: 100px; + } + + /* Adjust font sizes for smaller screens */ + fieldset, + #message, + li, + .results { + font-size: 14px; + } + + legend { + font-size: 20px; + } + + h2 { + font-size: 25px; + } + + /* Adjust box width for smaller screens */ + .box { + width: 95%; + } + } + + /* Media Query for medium screens (max-width: 900px) */ + @media screen and (max-width: 900px) { + /* Adjust box width for medium screens */ + .box { + width: 75%; + } + } + /* End of CSS */ + \ No newline at end of file