Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
const question = document.querySelector('#question');
const choices = Array.from(document.querySelectorAll('.choice-text'));
const progressText = document.querySelector('#progressText');
const scoreText = document.querySelector('#score');
const progressBarFull = document.querySelector('#progressBarFull');

let currentQuestion = {}
let acceptingAnswers = true
let score = 0
let questionCounter = 0
let availableQuestions = []

let questions = [
    {
        question: 'What is 2 + 2?',
        choice1: '2',
        choice2: '4',
        choice3: '21',
        choice4: '17',
        answer: 2,
    },
    {
        question:
            "The tallest building in the world is located in which city?",
        choice1: "Dubai",
        choice2: "New York",
        choice3: "Shanghai",
        choice4: "None of the above",
        answer: 1,
    },
    {
        question: "What percent of American adults believe that chocolate milk comes from brown cows?",
        choice1: "20%",
        choice2: "18%",
        choice3: "7%",
        choice4: "33%",
        answer: 3,
    },
    {
        question: "Approximately what percent of U.S. power outages are caused by squirrels?",
        choice1: "10-20%",
        choice2: "5-10%",
        choice3: "15-20%",
        choice4: "30%-40%",
        answer: 1,
    }
]

const SCORE_POINTS = 100
const MAX_QUESTIONS = 4

startGame = () => {
    questionCounter = 0
    score = 0
    availableQuestions = [...questions]
    getNewQuestion()
}

getNewQuestion = () => {
    if(availableQuestions.length === 0 || questionCounter > MAX_QUESTIONS) {
        localStorage.setItem('mostRecentScore', score)

        return window.location.assign('/end.html')
    }

    questionCounter++
    progressText.innerText = `Question ${questionCounter} of ${MAX_QUESTIONS}`
    progressBarFull.style.width = `${(questionCounter/MAX_QUESTIONS) * 100}%`
    
    const questionsIndex = Math.floor(Math.random() * availableQuestions.length)
    currentQuestion = availableQuestions[questionsIndex]
    question.innerText = currentQuestion.question

    choices.forEach(choice => {
        const number = choice.dataset['number']
        choice.innerText = currentQuestion['choice' + number]
    })

    availableQuestions.splice(questionsIndex, 1)

    acceptingAnswers = true
}

choices.forEach(choice => {
    choice.addEventListener('click', e => {
        if(!acceptingAnswers) return

        acceptingAnswers = false
        const selectedChoice = e.target
        const selectedAnswer = selectedChoice.dataset['number']

        let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect'

        if(classToApply === 'correct') {
            incrementScore(SCORE_POINTS)
        }

        selectedChoice.parentElement.classList.add(classToApply)

        setTimeout(() => {
            selectedChoice.parentElement.classList.remove(classToApply)
            getNewQuestion()

        }, 1000)
    })
})

incrementScore = num => {
    score +=num
    scoreText.innerText = score
}

startGame()


What I have tried:

like if have total number of 4 question only 3 should be asked from the quiz taker
Posted
Updated 9-Aug-21 12:35pm
Comments
sonar roy 15-Aug-21 13:26pm    
Thanks. https://www.fiverr.com/share/r9PZEP

To be honest, I wouldn't do it in Javascript - I'd do it in the backend code.
Why? Simple: if you do it in the JS, anyone taking your quiz can get a perfect score simply by asking the browser to look at the source code ... a right click or F12 and you're away!

But if you must, then have a look at this: How to select a random element from array in JavaScript ? - GeeksforGeeks[^]
 
Share this answer
 
Comments
Anime اردو 2021 3-Aug-21 23:57pm    
i want to know the backend method if you could link me to article or something
OriginalGriff 4-Aug-21 1:53am    
That will depend on the language you are using in the server: start with Google and look for that language and "Random select from an array".
John James 2023 13-Jul-23 14:36pm    
Would it matter if its a mobile app?
OriginalGriff 13-Jul-23 15:25pm    
Would what matter?
John James 2023 14-Jul-23 2:12am    
Having the questions on JS, as you said users can access the source code on browsers
Would they be able to access source code on mobile app?
I would try something like this:
myArray contains all questions
myCnt = myArray.length
randomTrivia = myArray[Math.floor(Math.random() * myCnt)];
document.getElementById('ptrivia').innerHTML = randomTrivia;
 
Share this answer
 
Quote:
like if have total number of 4 question only 3 should be asked from the quiz taker

Your random is to draw 3 questions out of 4 in random order, with no repeat, the trick is that this is not random, it is shuffle.
Think of a deck of cards. First you shuffle the deck of card, then you draw the first n cards. It comes in random sequence and with no repeat.
Shuffle a given array using Fisher–Yates shuffle Algorithm - GeeksforGeeks[^]
Fisher–Yates shuffle - Wikipedia[^]

Since it is a web app, this imply a few things:
- you need to keep track of a shuffle result per user taking the quizz at same time.
- need to keep track user score as user answer questions, and number of questions remaining.
- it is a bad idea to embed the answer in the web page, a curious user can just read the answers in the source code of the page.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900