Scritp
Scritp
{
question: "Cual es el disco musical más vendido de la historia",
answers: [
{ text: "1 The Beatles", correct: false},
{ text: "Romances Luis Miguel", correct: false},
{ text: "Back in Black AC/DC", correct: false},
{ text: "Thriller Michael Jackson", correct: true},
]
},
{
question: "A que velocidad viaja la luz",
answers: [
{ text: "299 792 458 m/s", correct: true},
{ text: "350 000 000 m/s", correct: false},
{ text: "245 300 108 m/s", correct: false},
{ text: "300 645 980 m/s", correct: false},
]
}
];
let currentQuestionIndex = 0;
let score = 0;
function startQuiz(){
currentQuestionIndex = 0;
score = 0;
nextButton.innerHTML = "Next";
showQuestion();
}
function showQuestion(){
restState();
let currentQuestion = questions[currentQuestionIndex];
let questionNo = currentQuestionIndex + 1;
questionElement.innerHTML = questionNo + ". " + currentQuestion.question;
currentQuestion.answers.forEach(answer => {
const button = document.createElement("button");
button.innerHTML = answer.text;
button.classList.add("btn");
answerButtons.appendChild(button);
if(answer.correct){
button.dataset.correct = answer.correct;
}
button.addEventListener("click", selectAnswer);
});
}
function restState(){
nextButton.style.display = "none";
while(answerButtons.firstChild){
answerButtons.removeChild(answerButtons.firstChild);
}
}
function selectAnswer(e){
const selectedBtn = e.target;
const isCorrect = selectedBtn.dataset.correct === "true";
if(isCorrect){
selectedBtn.classList.add("correct");
score++;
}else{
selectedBtn.classList.add("incorrect");
}
Array.from(answerButtons.children).forEach(button => {
if(button.dataset.correct === "true"){
button.classList.add("correct");
}
button.disabled = true;
});
nextButton.style.display = "block";
function showScore(){
restState();
questionElement.innerHTML = `Su puntaje ${score} de ${questions.length}!`;
nextButton.innerHTML = "Juega otra vez";
nextButton.style.display = "block";
}
function handleNextButton(){
currentQuestionIndex++;
if(currentQuestionIndex < questions.length){
showQuestion();
}else{
showScore();
}
}
nextButton.addEventListener("click", ()=>{
if(currentQuestionIndex < questions.length){
handleNextButton();
}else{
startQuiz();
}
});
startQuiz();