2

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>

1
  • (offtopic) instead of repeating true / false for correct ad absurdum, simply add it as a single property after question: i.e: correct: 3 where 3 is the index of the correct answer ;) Commented Feb 21, 2021 at 22:56

1 Answer 1

2

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()

Sign up to request clarification or add additional context in comments.

14 Comments

Yes, I have edited my original post to make it more clear. You need to define the variable with the other ones like shown above. eg. var correctAnswers = 0 Also, don't forget to reset correctAnswers back to zero after displaying it.
yes, the element variable should be linking to a div or something. This is the place that displays the score e.g. 7/10.
Sorry for the late answer. Ok, so first you need to add a place where you are going to display the text. in your HTML, right under the block saying <div class="container">, add: <div class="resultBox"></div>. Tell me when you are done so we can move on to the next step.
Nice, now you need some CSS. I am not the best with styling, so this is not going to look really good, but add this in your CSS right under the CSS for .start-btn, .next-btn: pastebin.com/tUuzgk6H Also, I forgot to mention that you need an id on the div we just created. so change <div class="resultBox"></div> to <div id="resultBox" class="resultBox"></div>. Sorry for the mistake!
I know that was a lot to take in, but if you have any questions, feel free to ask!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.