I was trying to display questions on html page rather on web dialog box using DOM of javascript but my codes is not working. The program is suppose to loop through the quiz in the js code and ask the questions without using dialog box, show whether the answer is right or wrong on the html page.
Here is the html codes:
var $question = document.getElementById("question");
var $feedback = document.getElementById("feedback");
var $score = document.getElementById("score");
quiz = {
name: "Super hero name quiz",
description: "How many super heroes can you name?",
question: "what is the real name of ",
questions: [{
question: "superman",
answer: "clarke kent"
},
{
question: "batman",
answer: "bruce wayne"
},
{
question: "wonder woman",
answer: "dianna prince"
}
]
};
play(quiz);
function update(element, content, klass) {
var p = element.firstChild ||
document.createElement("p");
p.textContent = content;
element.appendChild("p");
if (klass) {
p.className = klass;
}
}
function play(quiz) {
var score = 0;
update($score, score);
for (i = 0; i < quiz.questions.length; i++) {
question = quiz.questions[i].question;
answer = ask(question);
check(answer);
}
gameOver();
}
function check(ans) {
if (ans === quiz.questions[i].answer) {
update($feedback, "correct!", "right");
score++;
update($score, score);
} else {
update($feedback, "Wrong!", "wrong");
}
}
function ask(question) {
update($question, quiz.question + question);
return prompt("Enter your answer: ");
}
function gameOver() {
update($question, "Game over, you scored" + score + "points");
}
<!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 href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<header>
<h1>QUIZ NINJA!!!</h1>
</header>
<section id="question"></section>
<section id="feedback"></section>
<p>Score: <strong id="score">0</strong></p>
<script type="text/javascript" src="chap6_dom.js"></script>
</body>
</html>