Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const question = document.getElementById("question");
- const options = Array.from(document.getElementsByClassName("option-text"));
- const scoreText = document.getElementById('score');
- const timeText = document.getElementById("finalCountdown");
- let secondsLeft = 20;
- const scoreNerf = 15;
- let currentQuestion = {};
- let score = 0;
- let availableQuestions = [];
- let questions = [
- {
- "question": "Placeholder - Answer is D",
- "option1": "a",
- "option2": "b",
- "option3": "c",
- "option4": "d",
- "answer": 4
- },
- {
- "question": "Placeholder - the answer is B",
- "option1": "a",
- "option2": "b",
- "option3": "c",
- "option4": "d",
- "answer": 2
- },
- {
- "question": "Placeholder - The answer is B",
- "option1": "a",
- "option2": "b",
- "option3": "c",
- "option4": "d",
- "answer": 2
- }
- ];
- startGame = () => {
- availableQuestions = [...questions];
- setTime();
- getNewQuestion();
- };
- getNewQuestion = () => {
- if (availableQuestions.length === 0) {
- return window.location.assign("end.html");
- }
- const questionList = Math.floor(Math.random() * availableQuestions.length);
- currentQuestion = availableQuestions[questionList];
- question.innerText = currentQuestion.question;
- options.forEach(option => {
- const number = option.dataset["number"];
- option.innerText = currentQuestion["option" + number];
- });
- availableQuestions.splice(questionList, 1);
- };
- options.forEach(option => {
- option.addEventListener("click", e => {
- const selectedOption = e.target;
- const selectedAnswer = selectedOption.dataset["number"];
- let classCorrect = 'correct';
- if (selectedAnswer != currentQuestion.answer) {
- classCorrect = 'incorrect';
- };
- selectedOption.parentElement.classList.add(classCorrect);
- console.log(classCorrect);
- if (classCorrect === 'incorrect') {
- secondsLeft -= scoreNerf;
- }
- setTimeout(() => {
- selectedOption.parentElement.classList.remove(classCorrect);//this is the removal of the class from the container element.
- getNewQuestion();
- }, 150);
- });
- });
- setTime = () => {
- const timerInterval = setInterval(function () {
- secondsLeft--;
- timeText.innerText = secondsLeft;
- if (secondsLeft <= 0) {
- secondsLeft = 0;
- return window.location.assign("end.html");
- } else if (availableQuestions.length === "") {
- clearInterval(timerInterval);
- return window.location.assign("end.html");
- }
- localStorage.setItem("yourScore", secondsLeft);
- }, 1000);
- };
- //call function to start quiz.
- startGame();
Advertisement
Add Comment
Please, Sign In to add comment