Koussay Hamdi
Koussay Hamdi

Reputation: 33

How To Add A Score Function To My Quiz Using JavaScript?

How to add a score at the end of my quiz. Example: "10/10" or "0/10" As you can see my code I Made The Static Part with HTML and CSS and The Dynamic Part With Javascript, I Looked For Hours to find a solution but nothing came to my mind. What I Want is: Finish by displaying the score with a little message saying "Congrats" Or "Bad Luck"

i hope you guys help as i am still a beginner, Thanks!

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')

let RandomQuestions, currentQuestion

startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
  currentQuestion++
  setNextQuestion()
})

function startGame() {
  startButton.classList.add('hide')
  RandomQuestions = questions.sort(() => Math.random() - .5)
  currentQuestion = 0
  questionContainerElement.classList.remove('hide')
  setNextQuestion()
}

function setNextQuestion() {
  resetState()
  showQuestion(RandomQuestions[currentQuestion])
}

function showQuestion(question) {
  questionElement.innerText = question.question
  question.answers.forEach(answer => {
    const button = document.createElement('button')
    button.innerText = answer.text
    button.classList.add('btn')
    if (answer.correct) {
      button.dataset.correct = answer.correct
    }
    button.addEventListener('click', selectAnswer)
    answerButtonsElement.appendChild(button)
  })
}

function resetState() {
  clearStatusClass(document.body)
  nextButton.classList.add('hide')
  while (answerButtonsElement.firstChild) {
    answerButtonsElement.removeChild(answerButtonsElement.firstChild)
  }
}

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (RandomQuestions.length > currentQuestion + 1) {
    nextButton.classList.remove('hide')
  } else {
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

function setStatusClass(element, correct) {
  clearStatusClass(element)
  if (correct) {
    element.classList.add('correct')
  } else {
    element.classList.add('wrong')
  }
}

function clearStatusClass(element) {
  element.classList.remove('correct')
  element.classList.remove('wrong')
}

const questions = [
  {
    question: 'What is the rarest blood type?',
    answers: [
      { text: 'AB-Negative', correct: true },
      { text: 'O', correct: false }
    ]
  },
  {
    question: 'What sport does Cristiano Ronaldo play?',
    answers: [
      { text: 'Football', correct: true },
      { text: 'Tennis', correct: false },
      { text: 'Skateboarding', correct: false },
      { text: 'Racing', correct: false }
    ]
  },
  {
    question: "“Keep Calm and Carry On” is the slogan of which nation?",
    answers: [
      { text: 'Britain', correct: true },
      { text: 'Switzerland', correct: false },
      { text: 'Japan', correct: false },
      { text: 'Germany', correct: false }
    ]
  },
  {
    question: '"Fe" is the chemical symbol for which element?',
    answers: [
      { text: 'Iron', correct: true },
      { text: 'Oxygene', correct: false },
      { text: 'Potassium', correct: false },
      { text: 'Gold', correct: false }
    ]
  }
]
*, *::before, *::after {
    box-sizing: border-box;
  }
  
  :root {
    --color-neutral: 200;
    --color-wrong: 0;
    --color-correct: 145;
  }
  
  body {
    --color: var(--color-neutral);
    padding: 0;
    margin: 0;
    display: flex;
    width: 100vw;
    height: 100vh;
    justify-content: center;
    align-items: center;
    background-color: hsl(var(--color), 100%, 20%);
  }
  
  
  .container {
    width: 800px;
    max-width: 80%;
    background-color: white;
    border-radius: 5px;
    padding: 10px;
    box-shadow: 0 0 10px 2px;
  }
  
  .btn-grid {
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 10px;
    margin: 20px 0;
  }
  
  .btn {
    --color: var(--color-neutral);
    border: 1px solid hsl(var(--color), 100%, 30%);
    background-color: hsl(var(--color), 100%, 50%);
    border-radius: 5px;
    padding: 5px 10px;
    color: white;
    outline: none;
  }
  
  .btn:hover {
    border-color: black;
  }
  
  .btn.correct {
    --color: var(--color-correct);
    color: black;
  }
  
  .btn.wrong {
    --color: var(--color-wrong);
  }
  
  .start-btn, .next-btn {
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 20px;
  }
  
  .controls {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .hide {
    display: none;
  }
  
  
  
  
  /* Background Styles Only */
  
  @import url('https://fonts.googleapis.com/css?family=Raleway');
  
  
  html {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #DFDFDF;
  }

  
  
  
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <script defer src="script.js"></script>
</head>
<body>
    <div class="container">
        <div id="question-container" class="hide">
          <div id="question">Question</div>
          <div id="answer-buttons" class="btn-grid">
            <button class="btn">Answer 1</button>
            <button class="btn">Answer 2</button>
            <button class="btn">Answer 3</button>
            <button class="btn">Answer 4</button>
          </div>
        </div>
        <div class="controls">
          <button id="start-btn" class="start-btn btn">Start</button>
          <button id="next-btn" class="next-btn btn hide">Next</button>
        </div>
      </div>

</body>
</html>

Upvotes: 2

Views: 1109

Answers (1)

mr noob
mr noob

Reputation: 365

Just create a variable that holds the number of correct answers, make it equal to 0:

const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')

let RandomQuestions, currentQuestion
var correctAnswers = 0

Change the selectAnswer(e) function like below:

function selectAnswer(e) {
  const selectedButton = e.target
  const correct = selectedButton.dataset.correct
  if (correct) {
     correctAnswers++
  }
  setStatusClass(document.body, correct)
  Array.from(answerButtonsElement.children).forEach(button => {
    setStatusClass(button, button.dataset.correct)
  })
  if (RandomQuestions.length > currentQuestion + 1) {
    nextButton.classList.remove('hide')
  } else {
    display(correctAnswers.toString() + "/" + RandomQuestions.length.toString())
    correctAnswers = 0
    startButton.innerText = 'Restart'
    startButton.classList.remove('hide')
  }
}

Of course, replace display() with something like element.innerText = correctAnswers.toString() + "/" + RandomQuestions.length.toString()

Upvotes: 2

Related Questions