SCSS
by cedric_tarou
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>My Quize App</title>
</head>
<body>
<section class="container">
<p id="question"></p>
<ul id="choices">
</ul>
<div id="btn" class="disabled">Next</div>
<section id="result">
<p>Score: 3/3</p>
<a href="">Replay</a>
</section>
</section>
</body>
</html>
SCSS
body {
background: #efdec1;
font-size: 14px;
font-family: Verdana, sans-serif;
.container {
width: 400px;
margin: 2rem auto;
background: #fff;
border-radius: 0.4rem;
padding: 1.6rem;
position: relative;
}
}
#question {
margin-bottom: 1.6rem;
font-weight: bold;
}
#choices {
list-style: none;
padding: 0rem;
margin-bottom: 1.6rem;
> li {
border: 1px solid #ccc;
border-radius: 0.4rem;
padding: 1rem;
margin-bottom: 1rem;
cursor: pointer;
&:hover {
background: #f8f8f8;
}
&.correct {
background: #d4edda;
border-color: #c3e6cb;
color: #155724;
font-weight: bold;
&::after {
content: '...correct!';
}
}
&.wrong {
background: #f8d8da;
border-color: #f5c6cb;
color: #721c24;
font-weight: bold;
&::after {
content: '...wrong!';
}
}
}
}
#btn {
background: #3498db;
padding: 0.8rem;
border-radius: 0.4rem;
cursor: pinter;
text-align: center;
color: #fff;
box-shadow: 0 4px 0 #2880bd;
&.disabled {
background: #ccc;
box-shadow: 0 4px 0 #bbb;
opacity: 0.7;
}
}
#result {
position: absolute;
width: 300px;
background: #fff;
padding: 30px;
box-shadow: 0 4px 8px rgba(0, 0, 0.2);
}
JavaScript
'use strict';
{
const question = document.getElementById('question');
const choices = document.getElementById('choices');
const btn = document.getElementById('btn');
const quizSet = [
{q: 'What is A?', c: ['A0', 'A1', 'A2']},
{q: 'What is B?', c: ['B0', 'B1', 'B2']},
{q: 'What is C?', c: ['C0', 'C1', 'C2']},
];
let currentNum = 0;
let isAnswered;
let score = 0;
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[j], arr[i]] = [arr[i], arr[j]];
}
return arr;
}
function checkAnswer(li) {
if (isAnswered) {
return;
}
isAnswered = true;
if (li.textContent === quizSet[currentNum].c[0]) {
li.classList.add('correct');
score++;
} else {
li.classList.add('wrong');
}
btn.classList.remove('disabled');
}
function setQuiz() {
isAnswered = false;
question.textContent = quizSet[currentNum].q;
while (choices.firstChild) {
choices.removeChild(choices.firstChild);
}
const shuffledChoices = shuffle([...quizSet[currentNum].c]);
shuffledChoices.forEach(choice => {
const li = document.createElement('li');
li.textContent = choice;
li.addEventListener('click', () => {
checkAnswer(li);
});
choices.appendChild(li);
});
if (currentNum === quizSet.length - 1) {
btn.textContent = 'Show Score';
}
}
setQuiz();
btn.addEventListener('click', () => {
if (btn.classList.contains('disabled')) {
return;
}
btn.classList.add('disabled');
if (currentNum === quizSet.length - 1) {
console.log(`Score: ${score} / ${quizSet.length}`);
} else {
currentNum++;
setQuiz();
}
});
}