101 lines
2.4 KiB
JavaScript
101 lines
2.4 KiB
JavaScript
let score = 0;
|
|
let currentQuestionIndex = 0;
|
|
|
|
let questions = [
|
|
{
|
|
question: "Was ist Event Bubbling?",
|
|
answers: ["Essen", "Trinken", "JavaScript-Verhalten"],
|
|
correctAnswer: 2,
|
|
},
|
|
{
|
|
question: "Wie groß ist Eiffelturm?",
|
|
answers: ["330 Meter", "289 Meter", "312 Meter"],
|
|
correctAnswer: 0,
|
|
},
|
|
{
|
|
question: "Wer hat JavaScript erstellt?",
|
|
answers: ["Brendan Eich", "Lebron James", "Lionel Messi"],
|
|
correctAnswer: 0,
|
|
},
|
|
];
|
|
|
|
function shuffleArray(questionArray)
|
|
{
|
|
let newArray = [questionArray.length];
|
|
let rng = getRandomNumber(questionArray.length);
|
|
for(i = 0; i < questionArray.length; i++)
|
|
{
|
|
do
|
|
{
|
|
rng = getRandomNumber(questionArray.length);
|
|
}
|
|
while(newArray.includes(questionArray[rng]));
|
|
newArray[i] = questionArray[rng]
|
|
}
|
|
|
|
return newArray;
|
|
}
|
|
|
|
function getRandomNumber(maxValue){
|
|
let val = Math.floor(Math.random() * maxValue)
|
|
if(val >= maxValue)
|
|
getRandomNumber(maxValue);
|
|
|
|
return Math.floor(Math.random() * maxValue);
|
|
}
|
|
|
|
|
|
|
|
function resetQuiz(){
|
|
document.getElementById("result").hidden = true;
|
|
currentQuestionIndex = 0;
|
|
score = 0;
|
|
showQuestions();
|
|
document.getElementById("quiz-container").hidden = false;
|
|
}
|
|
|
|
|
|
function showQuestions() {
|
|
|
|
shuffledQuestions = shuffleArray(questions);
|
|
|
|
|
|
let btn = document.getElementById("resultBtn");
|
|
if (currentQuestionIndex >= shuffledQuestions.length) {
|
|
document.getElementById("quiz-container").hidden = true;
|
|
document.getElementById("result").hidden = false;
|
|
document.getElementById("score").textContent = score;
|
|
|
|
btn.hidden = false;
|
|
return;
|
|
}
|
|
|
|
let currentQuestion = shuffledQuestions[currentQuestionIndex];
|
|
|
|
|
|
document.getElementById("question").textContent = currentQuestion.question;
|
|
|
|
let answersDiv = document.getElementById("answers");
|
|
answersDiv.innerHTML = "";
|
|
|
|
currentQuestion.answers.forEach((answer, index ) => {
|
|
let answerBtn = document.createElement("button");
|
|
answerBtn.textContent = answer;
|
|
answerBtn.onclick = () => checkAnswer(index, currentQuestion.correctAnswer);
|
|
answersDiv.appendChild(answerBtn);
|
|
});
|
|
|
|
};
|
|
|
|
function checkAnswer(selectedIndex, indexOfCorrectAnswer) {
|
|
|
|
/*const correctAnswer = questions[currentQuestionIndex].correctAnswer;*/
|
|
if(selectedIndex === indexOfCorrectAnswer){
|
|
score++;
|
|
}
|
|
|
|
currentQuestionIndex++;
|
|
showQuestions();
|
|
}
|
|
|
|
showQuestions(); |