How can I prevent users from selecting multiple answers in my quiz? - javascript

The issue that I am having is that once a user selects an answer and then clicks 'Submit Answer' and receives their feedback they are able to continue to click around and select other answers before progressing onto the next question. How can I prevent a user from being able to do that once they submit one answer?
let score = 0;
let currentQuestion = 0;
let questions = [{
title: "At what age was Harry Potter when he received his Hogwarts letter?",
answers: ['7', '10', '11', '13'],
correct: 1
},
{
title: "Which is not a Hogwarts house?",
answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'],
correct: 0
},
{
title: "Who teaches Transfiguration at Hogwarts?",
answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'],
correct: 3
},
{
title: "Where is Hogwarts School for Witchcraft and Wizardry located?",
answers: ['France', 'USA', 'UK', 'New Zealand'],
correct: 2
},
{
title: "What form does Harry Potter's patronus charm take?",
answers: ['Stag', 'Eagle', 'Bear', 'Dragon'],
correct: 0
},
{
title: "What type of animal is Harry's pet?",
answers: ['Dog', 'Owl', 'Cat', 'Snake'],
correct: 1
},
{
title: "Who is not a member of the Order of the Phoenix?",
answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'],
correct: 2
},
{
title: "What is not a piece of the Deathly Hallows?",
answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'],
correct: 3
},
{
title: "In which house is Harry sorted into after arriving at Hogwarts?",
answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'],
correct: 2
},
{
title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?",
answers: ['Love', 'Anger', 'Friendship', 'Joy'],
correct: 0
},
];
$(document).ready(function() {
$('.start a').click(function(e) {
e.preventDefault();
$('.start').hide();
$('.quiz').show();
showQuestion();
});
$('.quiz').on('click', 'button', function() {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
$('.quiz a.submit').click(function(e) {
e.preventDefault();
if ($('button.selected').length) {
let guess = parseInt($('button.selected').attr('id'));
checkAnswer(guess);
} else {
alert('Please select an answer');
}
});
$('.summary a').click(function(e) {
e.preventDefault();
restartQuiz();
});
});
function showQuestion() {
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz div:nth-child(2)').html('');
for (var i = 0; i < question.answers.length; i++) {
$('.quiz div:nth-child(2)').append(`<button id="${i}">${question.answers[i]}</button>`);
}
showProgress();
}
function showIncorrectQuestion(guess) {
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz div:nth-child(2)').html('');
for (var i = 0; i < question.answers.length; i++) {
let cls = i === question.correct ? "selected" : guess === i ? "wrong" : ""
$('.quiz div:nth-child(2)').append(`<button id="${i}" class="${cls}">${question.answers[i]}</button>`);
}
showProgress();
}
function checkAnswer(guess) {
let question = questions[currentQuestion];
if (question.correct === guess) {
if (!question.alreadyAnswered) {
score++;
}
showIsCorrect(true);
} else {
showIsCorrect(false);
showIncorrectQuestion(guess);
}
question.alreadyAnswered = true;
}
function showSummary() {
$('.quiz').hide();
$('.summary').show();
$('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?")
}
function restartQuiz() {
questions.forEach(q => q.alreadyAnswered = false);
$('.summary').hide();
$('.quiz').show();
score = 0;
currentQuestion = 0;
showQuestion();
}
function showProgress() {
$('#currentQuestion').html(currentQuestion + " out of " + questions.length);
}
function showIsCorrect(isCorrect) {
var result = "Wrong";
if (isCorrect) {
result = "Correct";
}
$('#isCorrect').html(result);
$('.navigate').show();
$('.submit').hide();
}
$('.navigate').click(function() {
currentQuestion++;
if (currentQuestion >= questions.length) {
showSummary();
} else {
showQuestion();
}
$('.navigate').hide();
$('.submit').show();
$('#isCorrect').html('');
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
text-decoration: none;
text-align: center;
background-color: #837F73;
}
h1 {
font-family: 'Poor Story', cursive;
background-color: #950002;
padding: 60px;
color: #FFAB0D;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
h2 {
font-family: 'Poor Story', cursive;
font-size: 30px;
padding: 60px;
background-color: #950002;
color: #FFAB0D;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
p {
font-family: 'Poor Story', cursive;
background-color: #FFAB0D;
font-size: 20px;
font-weight: bold;
}
a {
border: 1px solid #222F5B;
padding: 10px;
background-color: #222F5B;
color: silver;
border-radius: 5px;
margin-top: 50px;
display: inline-block;
}
a:hover {
border: 1px solid #000000;
background-color: #000000;
color: #FCBF2B;
}
.quiz button {
cursor: pointer;
border: 1px solid;
display: inline-block;
width: 200px;
margin: 10px;
font-family: 'Poor Story', cursive;
font-size: 26px;
}
#currentQuestion {
color: #000000;
font-size: 18px;
font-family: 'Poor Story', cursive;
margin-top: 10px;
}
#isCorrect {
color: white;
font-family: 'Poor Story', cursive;
font-weight: bold;
font-size: 18px;
}
.quiz,
.summary {
display: none;
}
.quiz ul {
margin-top: 20px;
list-style: none;
padding: 0;
}
.selected {
background-color: #398C3F;
}
.wrong {
background-color: red;
}
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet">
<link href="style.css" rel="stylesheet" type="text/css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Harry Potter Quiz</title>
</head>
<body>
<header role="banner">
<div class="start">
<h1>How Well Do You Know Harry Potter?</h1>
Start Quiz
</div>
</header>
<main role="main">
<div class="quiz">
<h2>Question Title</h2>
<div>
<button>Choice</button>
<button>Choice</button>
<button>Choice</button>
<button>Choice</button>
</div>
<a class="submit" href="#">Submit Answer</a>
<a class="navigate" style="display:none;" href="#">Next Question</a>
<div id="currentQuestion"></div>
<footer role="contentinfo">
<div id="isCorrect"></div>
</footer>
</div>
</main>
<div class="summary">
<h2>Results</h2>
<p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p>
Retake Quiz
</div>
<script src="index.js"></script>
<!--jQuery script when using JSBin-->
<!--<script src="https://code.jquery.com/jquery-3.1.0.js"></script>-->
</body>
</html>

I have declared a variable called buttonClickable and used it as a flag on every button click. when the user submits the answer, buttonclickable turns false and when ever you are rendering a new question buttonclickable turns true.
let score = 0;
let currentQuestion = 0;
let buttonClickable = true;
let questions = [{
title: "At what age was Harry Potter when he received his Hogwarts letter?",
answers: ['7', '10', '11', '13'],
correct: 1
},
{
title: "Which is not a Hogwarts house?",
answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'],
correct: 0
},
{
title: "Who teaches Transfiguration at Hogwarts?",
answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'],
correct: 3
},
{
title: "Where is Hogwarts School for Witchcraft and Wizardry located?",
answers: ['France', 'USA', 'UK', 'New Zealand'],
correct: 2
},
{
title: "What form does Harry Potter's patronus charm take?",
answers: ['Stag', 'Eagle', 'Bear', 'Dragon'],
correct: 0
},
{
title: "What type of animal is Harry's pet?",
answers: ['Dog', 'Owl', 'Cat', 'Snake'],
correct: 1
},
{
title: "Who is not a member of the Order of the Phoenix?",
answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'],
correct: 2
},
{
title: "What is not a piece of the Deathly Hallows?",
answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'],
correct: 3
},
{
title: "In which house is Harry sorted into after arriving at Hogwarts?",
answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'],
correct: 2
},
{
title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?",
answers: ['Love', 'Anger', 'Friendship', 'Joy'],
correct: 0
},
];
$(document).ready(function() {
$('.start a').click(function(e) {
e.preventDefault();
$('.start').hide();
$('.quiz').show();
showQuestion();
});
$('.quiz').on('click', 'button', function() {
if(!buttonClickable) return;
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
$('.quiz a.submit').click(function(e) {
e.preventDefault();
if ($('button.selected').length) {
let guess = parseInt($('button.selected').attr('id'));
checkAnswer(guess);
} else {
alert('Please select an answer');
}
});
$('.summary a').click(function(e) {
e.preventDefault();
restartQuiz();
});
});
function showQuestion() {
buttonClickable = true;
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz div:nth-child(2)').html('');
for (var i = 0; i < question.answers.length; i++) {
$('.quiz div:nth-child(2)').append(`<button id="${i}">${question.answers[i]}</button>`);
}
showProgress();
}
function showIncorrectQuestion(guess) {
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz div:nth-child(2)').html('');
for (var i = 0; i < question.answers.length; i++) {
let cls = i === question.correct ? "selected" : guess === i ? "wrong" : ""
$('.quiz div:nth-child(2)').append(`<button id="${i}" class="${cls}">${question.answers[i]}</button>`);
}
showProgress();
}
function checkAnswer(guess) {
buttonClickable = false;
let question = questions[currentQuestion];
if (question.correct === guess) {
if (!question.alreadyAnswered) {
score++;
}
showIsCorrect(true);
} else {
showIsCorrect(false);
showIncorrectQuestion(guess);
}
question.alreadyAnswered = true;
}
function showSummary() {
$('.quiz').hide();
$('.summary').show();
$('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?")
}
function restartQuiz() {
questions.forEach(q => q.alreadyAnswered = false);
$('.summary').hide();
$('.quiz').show();
score = 0;
currentQuestion = 0;
showQuestion();
}
function showProgress() {
$('#currentQuestion').html(currentQuestion + " out of " + questions.length);
}
function showIsCorrect(isCorrect) {
var result = "Wrong";
if (isCorrect) {
result = "Correct";
}
$('#isCorrect').html(result);
$('.navigate').show();
$('.submit').hide();
}
$('.navigate').click(function() {
currentQuestion++;
if (currentQuestion >= questions.length) {
showSummary();
} else {
showQuestion();
}
$('.navigate').hide();
$('.submit').show();
$('#isCorrect').html('');
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
text-decoration: none;
text-align: center;
background-color: #837F73;
}
h1 {
font-family: 'Poor Story', cursive;
background-color: #950002;
padding: 60px;
color: #FFAB0D;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
h2 {
font-family: 'Poor Story', cursive;
font-size: 30px;
padding: 60px;
background-color: #950002;
color: #FFAB0D;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
p {
font-family: 'Poor Story', cursive;
background-color: #FFAB0D;
font-size: 20px;
font-weight: bold;
}
a {
border: 1px solid #222F5B;
padding: 10px;
background-color: #222F5B;
color: silver;
border-radius: 5px;
margin-top: 50px;
display: inline-block;
}
a:hover {
border: 1px solid #000000;
background-color: #000000;
color: #FCBF2B;
}
.quiz button {
cursor: pointer;
border: 1px solid;
display: inline-block;
width: 200px;
margin: 10px;
font-family: 'Poor Story', cursive;
font-size: 26px;
}
#currentQuestion {
color: #000000;
font-size: 18px;
font-family: 'Poor Story', cursive;
margin-top: 10px;
}
#isCorrect {
color: white;
font-family: 'Poor Story', cursive;
font-weight: bold;
font-size: 18px;
}
.quiz,
.summary {
display: none;
}
.quiz ul {
margin-top: 20px;
list-style: none;
padding: 0;
}
.selected {
background-color: #398C3F;
}
.wrong {
background-color: red;
}
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet">
<link href="style.css" rel="stylesheet" type="text/css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Harry Potter Quiz</title>
</head>
<body>
<header role="banner">
<div class="start">
<h1>How Well Do You Know Harry Potter?</h1>
Start Quiz
</div>
</header>
<main role="main">
<div class="quiz">
<h2>Question Title</h2>
<div>
<button>Choice</button>
<button>Choice</button>
<button>Choice</button>
<button>Choice</button>
</div>
<a class="submit" href="#">Submit Answer</a>
<a class="navigate" style="display:none;" href="#">Next Question</a>
<div id="currentQuestion"></div>
<footer role="contentinfo">
<div id="isCorrect"></div>
</footer>
</div>
</main>
<div class="summary">
<h2>Results</h2>
<p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p>
Retake Quiz
</div>
<script src="index.js"></script>
<!--jQuery script when using JSBin-->
<!--<script src="https://code.jquery.com/jquery-3.1.0.js"></script>-->
</body>
</html>

Having skimmed through your JS, I'm assuming that the feedback shows on the same page as the question, rather than a new page resulting from submitting it to a server.
When you display the feedback, add a disabled="disabled" property to the item in question, so that your user can't change it. Alternately, hide the selection and display an <output> element: <output>Your Answer: USA<br />Correct Answer: UK</output>

disable All button after checking answers.
$('button').prop('disabled', true);

Related

What did i do wrong in this JavaScript code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I am learning javascript nowadays and i am trying to make a word scramble game via youtube video. When i hit check it always says not correct how can i fix this problem ? What did i do wrong ? (This is my first entry if i do something wrong or deficent please let me know + sorry for my bad english :) )
const wordText = document.querySelector(".word"),
hintText = document.querySelector(".hint span"),
inputField = document.querySelector(".input"),
refreshBtn = document.querySelector(".refresh-word"),
checkBtn = document.querySelector(".check-word");
// Words/Kelimeler
const words = [
{
word: "addition",
hint: "The process of adding numbers",
},
{
word: "meeting",
hint: "Event in which people come together",
},
{
word: "number",
hint: "Math symbol used for counting",
},
{
word: "exchange",
hint: "The act of trading",
},
{
word: "canvas",
hint: "Piece of fabric for oil painting",
},
{
word: "garden",
hint: "Space for planting flower and plant",
},
{
word: "position",
hint: "Location of someone or something",
},
{
word: "feather",
hint: "Hair like outer covering of bird",
},
{
word: "comfort",
hint: "A pleasant feeling of relaxation",
},
{
word: "tongue",
hint: "The muscular organ of mouth",
},
{
word: "expansion",
hint: "The process of increase or grow",
},
{
word: "country",
hint: "A politically identified region",
},
{
word: "group",
hint: "A number of objects or persons",
},
{
word: "taste",
hint: "Ability of tongue to detect flavour",
},
{
word: "store",
hint: "Large shop where goods are traded",
},
{
word: "field",
hint: "Area of land for farming activities",
},
{
word: "friend",
hint: "Person other than a family member",
},
{
word: "pocket",
hint: "A bag for carrying small items",
},
{
word: "needle",
hint: "A thin and sharp metal pin",
},
{
word: "expert",
hint: "Person with extensive knowledge",
},
{
word: "statement",
hint: "A declaration of something",
},
{
word: "second",
hint: "One-sixtieth of a minute",
},
{
word: "library",
hint: "Place containing collection of books",
},
];
let correctWord;
const initGame = () => {
let randomObj = words[Math.floor(Math.random() * words.length)]; //kelimelerden rastgele obje alma /getting random object from words
let wordArray = randomObj.word.split(""); //Splitting each letter of random word / her kelimeyi rastgele harflere böler
for (let i = wordArray.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1)); //rastgele sayı alma /geting random num
let temp = wordArray[i];
wordArray[i] = wordArray[j];
wordArray[j] = temp;
}
wordText.innerText = wordArray.join(""); //ayırdığımız kelimelerin boşluklarını neyle bağlıyacağımızı seçiyoruz/passing shuffled word as word text
hintText.innerText = randomObj.hint;
correctWord = randomObj.word.toLowerCase;
console.log(randomObj);
};
const checkWord = () => {
let userWord = inputField.value.toLocaleLowerCase();
console.log(userWord);
if (userWord !== correctWord)
return alert(`Oops! ${userWord} is not correct word`);
alert(`Congrats! ${userWord.toUpperCase()} is correct`);
if (!userWord) return alert(`Please enter word`);
};
refreshBtn.addEventListener("click", initGame);
checkBtn.addEventListener("click", checkWord);
initGame();
#import url("https://fonts.googleapis.com/css2?family=Poppins:wght#400;500;600&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #2c3333;
}
.container {
width: 450px;
background: #fff;
border-radius: 7px;
}
.container h2 {
font-size: 25px;
font-weight: 500;
padding: 18px 25px;
border-bottom: 1px solid #ccc;
}
.container .content {
margin: 25px 20px 35px;
}
.content .word {
font-size: 33px;
font-weight: 500;
text-align: center;
text-transform: uppercase;
letter-spacing: 25px;
margin-right: -25px;
}
.content .details {
margin: 25px 0 20px;
}
.details p {
font-size: 18px;
margin-bottom: 10px;
}
.details p b {
font-weight: 500;
}
.content input {
width: 100%;
height: 60px;
outline: none;
padding: 0 16px;
border-radius: 5px;
border: 1px solid #aaa;
font-size: 18px;
}
.content .buttons {
display: flex;
margin-top: 20px;
justify-content: space-between;
}
.buttons button {
border: none;
outline: none;
padding: 15px 0;
color: white;
cursor: pointer;
font-size: 17px;
border-radius: 5px;
width: calc(100% / 2- 8px);
}
.buttons .check-word {
background: #a0d995;
padding-left: 30px;
padding-right: 30px;
}
.buttons .refresh-word {
background: #a5c9ca;
padding-left: 30px;
padding-right: 30px;
}
<!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>Word Scramble Game</title>
<link rel="stylesheet" href="style.css" />
<script src="js/script.js" defer></script>
</head>
<body>
<div class="container">
<h2>Word Scramble Game</h2>
<div class="content">
<p class="word"></p>
<div class="details">
<p class="hint">Hint:<span></span></p>
<p class="time">
Time Left:<span><b>30</b>s</span>
</p>
</div>
<input class="input" type="text" placeholder="Enter a valid word" />
<div class="buttons">
<button class="refresh-word">Refresh Word</button>
<button class="check-word">Check Word</button>
</div>
</div>
</div>
</body>
</html>
toLowerCase is a function, not a property, so you need to add parenthesis.
correctWord = randomObj.word.toLowerCase();
const wordText = document.querySelector(".word"),
hintText = document.querySelector(".hint span"),
inputField = document.querySelector(".input"),
refreshBtn = document.querySelector(".refresh-word"),
checkBtn = document.querySelector(".check-word");
// Words/Kelimeler
const words = [
{
word: "addition",
hint: "The process of adding numbers",
},
{
word: "meeting",
hint: "Event in which people come together",
},
{
word: "number",
hint: "Math symbol used for counting",
},
{
word: "exchange",
hint: "The act of trading",
},
{
word: "canvas",
hint: "Piece of fabric for oil painting",
},
{
word: "garden",
hint: "Space for planting flower and plant",
},
{
word: "position",
hint: "Location of someone or something",
},
{
word: "feather",
hint: "Hair like outer covering of bird",
},
{
word: "comfort",
hint: "A pleasant feeling of relaxation",
},
{
word: "tongue",
hint: "The muscular organ of mouth",
},
{
word: "expansion",
hint: "The process of increase or grow",
},
{
word: "country",
hint: "A politically identified region",
},
{
word: "group",
hint: "A number of objects or persons",
},
{
word: "taste",
hint: "Ability of tongue to detect flavour",
},
{
word: "store",
hint: "Large shop where goods are traded",
},
{
word: "field",
hint: "Area of land for farming activities",
},
{
word: "friend",
hint: "Person other than a family member",
},
{
word: "pocket",
hint: "A bag for carrying small items",
},
{
word: "needle",
hint: "A thin and sharp metal pin",
},
{
word: "expert",
hint: "Person with extensive knowledge",
},
{
word: "statement",
hint: "A declaration of something",
},
{
word: "second",
hint: "One-sixtieth of a minute",
},
{
word: "library",
hint: "Place containing collection of books",
},
];
let correctWord;
const initGame = () => {
let randomObj = words[Math.floor(Math.random() * words.length)]; //kelimelerden rastgele obje alma /getting random object from words
let wordArray = randomObj.word.split(""); //Splitting each letter of random word / her kelimeyi rastgele harflere böler
for (let i = wordArray.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1)); //rastgele sayı alma /geting random num
let temp = wordArray[i];
wordArray[i] = wordArray[j];
wordArray[j] = temp;
}
wordText.innerText = wordArray.join(""); //ayırdığımız kelimelerin boşluklarını neyle bağlıyacağımızı seçiyoruz/passing shuffled word as word text
hintText.innerText = randomObj.hint;
correctWord = randomObj.word.toLowerCase();
};
const checkWord = () => {
let userWord = inputField.value.toLocaleLowerCase();
if (userWord !== correctWord)
return alert(`Oops! ${userWord} is not correct word`);
alert(`Congrats! ${userWord.toUpperCase()} is correct`);
if (!userWord) return alert(`Please enter word`);
};
refreshBtn.addEventListener("click", initGame);
checkBtn.addEventListener("click", checkWord);
initGame();
#import url("https://fonts.googleapis.com/css2?family=Poppins:wght#400;500;600&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #2c3333;
}
.container {
width: 450px;
background: #fff;
border-radius: 7px;
}
.container h2 {
font-size: 25px;
font-weight: 500;
padding: 18px 25px;
border-bottom: 1px solid #ccc;
}
.container .content {
margin: 25px 20px 35px;
}
.content .word {
font-size: 33px;
font-weight: 500;
text-align: center;
text-transform: uppercase;
letter-spacing: 25px;
margin-right: -25px;
}
.content .details {
margin: 25px 0 20px;
}
.details p {
font-size: 18px;
margin-bottom: 10px;
}
.details p b {
font-weight: 500;
}
.content input {
width: 100%;
height: 60px;
outline: none;
padding: 0 16px;
border-radius: 5px;
border: 1px solid #aaa;
font-size: 18px;
}
.content .buttons {
display: flex;
margin-top: 20px;
justify-content: space-between;
}
.buttons button {
border: none;
outline: none;
padding: 15px 0;
color: white;
cursor: pointer;
font-size: 17px;
border-radius: 5px;
width: calc(100% / 2- 8px);
}
.buttons .check-word {
background: #a0d995;
padding-left: 30px;
padding-right: 30px;
}
.buttons .refresh-word {
background: #a5c9ca;
padding-left: 30px;
padding-right: 30px;
}
<!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>Word Scramble Game</title>
<link rel="stylesheet" href="style.css" />
<script src="js/script.js" defer></script>
</head>
<body>
<div class="container">
<h2>Word Scramble Game</h2>
<div class="content">
<p class="word"></p>
<div class="details">
<p class="hint">Hint:<span></span></p>
<p class="time">
Time Left:<span><b>30</b>s</span>
</p>
</div>
<input class="input" type="text" placeholder="Enter a valid word" />
<div class="buttons">
<button class="refresh-word">Refresh Word</button>
<button class="check-word">Check Word</button>
</div>
</div>
</div>
</body>
</html>
You are missing parentheses see my comment in code on line 116
const wordText = document.querySelector(".word"),
hintText = document.querySelector(".hint span"),
inputField = document.querySelector(".input"),
refreshBtn = document.querySelector(".refresh-word"),
checkBtn = document.querySelector(".check-word");
// Words/Kelimeler
const words = [{
word: "addition",
hint: "The process of adding numbers",
},
{
word: "meeting",
hint: "Event in which people come together",
},
{
word: "number",
hint: "Math symbol used for counting",
},
{
word: "exchange",
hint: "The act of trading",
},
{
word: "canvas",
hint: "Piece of fabric for oil painting",
},
{
word: "garden",
hint: "Space for planting flower and plant",
},
{
word: "position",
hint: "Location of someone or something",
},
{
word: "feather",
hint: "Hair like outer covering of bird",
},
{
word: "comfort",
hint: "A pleasant feeling of relaxation",
},
{
word: "tongue",
hint: "The muscular organ of mouth",
},
{
word: "expansion",
hint: "The process of increase or grow",
},
{
word: "country",
hint: "A politically identified region",
},
{
word: "group",
hint: "A number of objects or persons",
},
{
word: "taste",
hint: "Ability of tongue to detect flavour",
},
{
word: "store",
hint: "Large shop where goods are traded",
},
{
word: "field",
hint: "Area of land for farming activities",
},
{
word: "friend",
hint: "Person other than a family member",
},
{
word: "pocket",
hint: "A bag for carrying small items",
},
{
word: "needle",
hint: "A thin and sharp metal pin",
},
{
word: "expert",
hint: "Person with extensive knowledge",
},
{
word: "statement",
hint: "A declaration of something",
},
{
word: "second",
hint: "One-sixtieth of a minute",
},
{
word: "library",
hint: "Place containing collection of books",
},
];
let correctWord;
const initGame = () => {
let randomObj = words[Math.floor(Math.random() * words.length)]; //kelimelerden rastgele obje alma /getting random object from words
let wordArray = randomObj.word.split(""); //Splitting each letter of random word / her kelimeyi rastgele harflere böler
for (let i = wordArray.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1)); //rastgele sayı alma /geting random num
let temp = wordArray[i];
wordArray[i] = wordArray[j];
wordArray[j] = temp;
}
wordText.innerText = wordArray.join(""); //ayırdığımız kelimelerin boşluklarını neyle bağlıyacağımızı seçiyoruz/passing shuffled word as word text
hintText.innerText = randomObj.hint;
correctWord = randomObj.word.toLowerCase(); // You are missing parentheses here
console.log(randomObj);
};
const checkWord = () => {
let userWord = inputField.value.toLocaleLowerCase();
console.log({userWord, correctWord});
if (userWord !== correctWord)
return alert(`Oops! ${userWord} is not correct word`);
alert(`Congrats! ${userWord.toUpperCase()} is correct`);
if (!userWord) return alert(`Please enter word`);
};
refreshBtn.addEventListener("click", initGame);
checkBtn.addEventListener("click", checkWord);
initGame();
#import url("https://fonts.googleapis.com/css2?family=Poppins:wght#400;500;600&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #2c3333;
}
.container {
width: 450px;
background: #fff;
border-radius: 7px;
}
.container h2 {
font-size: 25px;
font-weight: 500;
padding: 18px 25px;
border-bottom: 1px solid #ccc;
}
.container .content {
margin: 25px 20px 35px;
}
.content .word {
font-size: 33px;
font-weight: 500;
text-align: center;
text-transform: uppercase;
letter-spacing: 25px;
margin-right: -25px;
}
.content .details {
margin: 25px 0 20px;
}
.details p {
font-size: 18px;
margin-bottom: 10px;
}
.details p b {
font-weight: 500;
}
.content input {
width: 100%;
height: 60px;
outline: none;
padding: 0 16px;
border-radius: 5px;
border: 1px solid #aaa;
font-size: 18px;
}
.content .buttons {
display: flex;
margin-top: 20px;
justify-content: space-between;
}
.buttons button {
border: none;
outline: none;
padding: 15px 0;
color: white;
cursor: pointer;
font-size: 17px;
border-radius: 5px;
width: calc(100% / 2- 8px);
}
.buttons .check-word {
background: #a0d995;
padding-left: 30px;
padding-right: 30px;
}
.buttons .refresh-word {
background: #a5c9ca;
padding-left: 30px;
padding-right: 30px;
}
<div class="container">
<h2>Word Scramble Game</h2>
<div class="content">
<p class="word"></p>
<div class="details">
<p class="hint">Hint:<span></span></p>
<p class="time">
Time Left:<span><b>30</b>s</span>
</p>
</div>
<input class="input" type="text" placeholder="Enter a valid word" />
<div class="buttons">
<button class="refresh-word">Refresh Word</button>
<button class="check-word">Check Word</button>
</div>
</div>
</div>
After a bit of JSFiddling, I logged when it set the correct answer and found that: You are setting the correctAnswer Variable to a function (specifically toLocaleLowercase. What you want is to call that function and set correctAnswer to the value: (ln 117)
correctWord = randomObj.word.toLocaleLowerCase()

Creating a score that will go up every time a correct answer is selected

So I have a quiz created using HTML, CSS, and javascript. I am trying to add a score but when I add to it when it goes to the next question then it either adds 4 each time or does not add. Any help appreciated
Javascript
const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')
var score = 0
score = Number(score)
let shuffledQuestions, currentQuestionIndex
startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
currentQuestionIndex++
setNextQuestion()
})
function startGame() {
startButton.classList.add('hide')
shuffledQuestions = questions.sort(() => Math.random() - .5)
currentQuestionIndex = 0
questionContainerElement.classList.remove('hide')
setNextQuestion()
}
function setNextQuestion() {
resetState()
showQuestion(shuffledQuestions[currentQuestionIndex])
}
function showQuestion(question) {
questionElement.innerText = question.question
question.answers.forEach(answer => {
const button = document.createElement('button')
button.innerText = answer.text
button.classList.add('btn')
if (answer.correct) {
//button.dataset.correct = answer.correct
answer.correct = Boolean(answer.correct)
button.dataset.correct = answer.correct
//mainbox .body.correct
//$("mainbox").css("background-color","green");
}
button.addEventListener('click', selectAnswer)
answerButtonsElement.appendChild(button)
})
}
function resetState() {
clearStatusClass(document.body)
nextButton.classList.add('hide')
while (answerButtonsElement.firstChild) {
answerButtonsElement.removeChild(answerButtonsElement.firstChild)
}
}
function selectAnswer(e) {
const selectedButton = e.target
const correct = selectedButton.dataset.correct
setStatusClass(document.body, correct)
Array.from(answerButtonsElement.children).forEach(button => {
setStatusClass(button, button.dataset.correct)
})
if (shuffledQuestions.length > currentQuestionIndex + 1) {
nextButton.classList.remove('hide')
} else {
startButton.innerText = 'Restart'
startButton.classList.remove('hide')
window.alert("You have scored "+ score)
score = 0;
score = Number(score);
}
}
function setStatusClass(element, correct) {
clearStatusClass(element)
if (correct) {
element.classList.add('correct')
} else {
element.classList.add('wrong')
}
}
function clearStatusClass(element) {
element.classList.remove('correct')
element.classList.remove('wrong')
}
const questions = [
{
question: 'which is non-price factor?',
answers: [
{ text: 'income', correct: true },
{ text: 'price ', correct: false }
]
},
{
question: 'which is merit good?',
answers: [
{ text: 'cigarette', correct: false },
{ text: 'junk food ', correct: false },
{ text: 'healthcare', correct: true },
{ text: 'gambling', correct: false }
]
},
{
question: 'which one is not the type of market failure?',
answers: [
{ text: 'monopoly market', correct: false },
{ text: 'oligopoly market', correct: true },
{ text: 'demerit goods', correct: false },
{ text: 'negative externality', correct: false }
]
},
{
question: 'Total profit = total revenue - total cost?',
answers: [
{ text: 'flase', correct: false },
{ text: 'true', correct: true }
]
}
]
Style Sheet
#topbox{
width: 100%;
height: 70px;
background-color: rgb(146, 182, 214);
}
u1 {
list-style-type: none ;
margin : 0px ;
padding : 0 ;
overflow : hidden;
background-color: rgb(153, 197, 218);
}
li {
float: left;
}
li a {
display:inline-block;
padding: 20px;
border: 1px solid rgb(243, 240, 240);
background-color: rgb(153, 197, 218);
color: white;
text-align:center;
position:relative;
padding-bottom: 20px;
font-size: 20pt;
}
#medianbox{
width: 100%;
height: 73px;
background-color:rgb(153, 197, 218) ;
}
#mainbox{
width: 100%;
height: 100%;
background-color: rgb(146, 182, 214);
}
*, *::before, *::after {
box-sizing: border-box;
font-family: Gotham Rounded; }
.root {
--hue-neutral: 200;
--hue-wrong: 0;
--hue-correct: 145; }
.body {
--hue: var(--hue-neutral);
padding: 10000px;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
justify-content: center;
align-items: center;
background-color: hsl(var(--hue), 100%, 20%); }
.body.correct {
hue: var(--hue-correct); }
.body.wrong {
--hue: var(--hue-wrong); }
.container {
width: 800px;
max-width: 80%;
background-color: white;
border-radius: 5px;
padding: 10px;
box-shadow: 0 0 10px 2px; }
.btn-grid {
display: grid;
grid-template-columns: repeat(2, auto);
gap: 10px;
margin: 20px 0;
Color: blue; }
.btn {
--hue: var(--hue-neutral);
border: 1px solid hsl(var(--hue), 100%, 30%); }
.btn:hover {
border-color: black; }
.btn.correct {
--hue: var(--hue-correct);
color: green; }
.btn.wrong {
--hue: var(--hue-wrong); }
.start-btn, .next-btn {
font-size: 1.5rem;
font-weight: bold;
padding: 10px 20px; }
.controls {
display: flex;
justify-content: center;
align-items: center; }
.hide {
display: flex; }
.p1 {
font-family: "Times New Roman", Times, serif;
font-size: 26pt;
}
HTML
Quiz App
BBS economic
definition
test
resource
community
search
me
Question
Answer 1
Answer 2
Answer 3
Answer 4
Start
Next
Consider this, If you're just creating a simple Quiz for practice.
var score_card = document.getElementById('score');
var score_no = 0;
function Calculate(){
if (document.getElementById('Q1sol3').checked == true){
score_no+=1
}
if (document.getElementById('Q2sol4').checked == true){
score_no+=1
}
score_card.innerHTML = score_no;
}
<!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>
</head>
<body>
<span>SCORE: <span id="score">0</span></span>
<br>
<section>
<div id="Q1">
<span>What is your Fav Tag?</span><br>
<input type="radio" name="Q1" id="Q1sol1">
<label for="Q1sol1">Body</label><br>
<input type="radio" name="Q1" id="Q1sol2">
<label for="Q1sol2">Head</label><br>
<input type="radio" name="Q1" id="Q1sol3">
<label for="Q1sol3">DIV</label><br>
<input type="radio" name="Q1" id="Q1sol4">
<label for="Q1sol4">HTML</label><br>
</div>
<br>
<div id="Q2">
<span>What is your Fav attribute?</span><br>
<input type="radio" name="Q2" id="Q2sol1">
<label for="Q2sol1">src</label><br>
<input type="radio" name="Q2" id="Q2sol2">
<label for="Q2sol2">href</label><br>
<input type="radio" name="Q2" id="Q2sol3">
<label for="Q2sol3">style</label><br>
<input type="radio" name="Q2" id="Q2sol4">
<label for="Q2sol4">id</label><br>
</div>
<br>
<br>
<input type="button" id="btn" onClick="Calculate()" style="background:green; color:white; padding:3px;" value="Submit">
</section>
</body>
</html>

Why won't my code display the score at the end of the quiz?

I am currently building a quiz game for my school project. The question is displayed and you have to click on the answer that you think is correct, the correct answer will be displayed in green and the wrong answers in red. after you complete the first randomized question there will be a next button which you will have to click to move on to the next question, once you complete all 5 questions there is a submit button. After you click the submit button the score should be displayed, however the score is not displaying.
This is the JavaScript:
const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')
const scoreText = document.getElementById("score");
let shuffledQuestions, currentQuestionIndex
let score = 0;
document.write(score);
startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
currentQuestionIndex++
setNextQuestion()
})
function startGame() {
startButton.classList.add('hide')
shuffledQuestions = questions.sort(() => Math.random() - .5)
currentQuestionIndex = 0
questionContainerElement.classList.remove('hide')
setNextQuestion()
}
function setNextQuestion() {
resetState()
showQuestion(shuffledQuestions[currentQuestionIndex])
}
function showQuestion(question) {
questionElement.innerText = question.question
question.answers.forEach(answer => {
const button = document.createElement('button')
button.innerText = answer.text
button.classList.add('btn')
if (answer.correct) {
button.dataset.correct = answer.correct
}
button.addEventListener('click', selectAnswer)
answerButtonsElement.appendChild(button)
})
}
function resetState() {
clearStatusClass(document.body)
nextButton.classList.add('hide')
while (answerButtonsElement.firstChild) {
answerButtonsElement.removeChild(answerButtonsElement.firstChild)
}
}
function selectAnswer(e) {
const selectedButton = e.target
const correct = selectedButton.dataset.correct
setStatusClass(document.body, correct)
Array.from(answerButtonsElement.children).forEach(button => {
setStatusClass(button, button.dataset.correct)
})
if (shuffledQuestions.length > currentQuestionIndex + 1) {
nextButton.classList.remove('hide')
} else {
startButton.innerText = 'Submit'
startButton.classList.remove('hide')
}
if (answer.correct) {
score++
}
}
function setStatusClass(element, correct) {
clearStatusClass(element)
if (correct) {
element.classList.add('correct')
} else {
element.classList.add('wrong')
}
}
function clearStatusClass(element) {
element.classList.remove('correct')
element.classList.remove('wrong')
}
const questions = [{
question: 'What is the capital city of Brazil?',
answers: [{
text: 'Brasilia',
correct: true
},
{
text: 'Rio de Janeiro',
correct: false
}
]
},
{
question: 'What is the population of the United Kingdom in 2021?',
answers: [{
text: '68 million',
correct: true
},
{
text: '81 million',
correct: false
},
{
text: '56 million',
correct: false
},
{
text: '62 million',
correct: false
}
]
},
{
question: 'What country has the most people as of 2021?',
answers: [{
text: 'India',
correct: false
},
{
text: 'Indonesia',
correct: false
},
{
text: 'China',
correct: true
},
{
text: 'USA',
correct: false
}
]
},
{
question: 'Which city is bigger?',
answers: [{
text: 'Paris',
correct: false
},
{
text: 'London',
correct: true
}
]
},
{
question: 'What country is angkor wat in?',
answers: [{
text: 'Laos',
correct: false
},
{
text: 'Cambodia',
correct: true
},
{
text: 'Vietnam',
correct: false
},
{
text: 'Thailand',
correct: false
}
]
}
]
{
//This is the bit where the score should have been displayed document.getElementById("after_submit").style.visibility="visible";
document.getElementById("score").innerHTML = "you got " + score + " correct.";
}
//This is the CSS:
*, *::before, *::after {
box-sizing: border-box;
font-family: Gotham Rounded;
}
:root {
--hue-neutral: 200;
--hue-wrong: 0;
--hue-correct: 145;
}
body {
--hue: var(--hue-neutral);
padding: 0;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
justify-content: center;
align-items: center;
background-color: lime;
}
body.correct {
--hue: var(--hue-correct);
}
body.wrong {
--hue: var(--hue-wrong);
}
.container {
width: 600px;
max-width: 80%;
background-color: green;
border-radius: 5px;
padding: 10px;
box-shadow: 0 0 10px 2px;
color: white;
}
.btn-grid {
display: grid;
grid-template-columns: repeat(2, auto);
gap: 10px;
margin: 20px 0;
}
.btn {
--hue: var(--hue-neutral);
border: 1px solid hsl(var(--hue), 100%, 30%);
background-color: hsl(var(--hue), 100%, 50%);
border-radius: 5px;
padding: 5px 10px;
color: white;
outline: none;
}
.btn:hover {
border-color: black;
}
.btn.correct {
--hue: var(--hue-correct);
color: white;
}
.btn.wrong {
--hue: var(--hue-wrong);
}
.start-btn, .next-btn {
font-size: 1.5rem;
font-weight: bold;
padding: 10px 20px;
}
.controls {
display: flex;
justify-content: center;
align-items: center;
}
a {
text-decoration: solid;
color: white;
font-size: 300%
}
div.a {
position: absolute;
top: 0;
border: green;
}
.hide {
display: none;
}
#after_Submit {
visibility: hidden;
}
<html lang="en">
<title>Quiz App</title>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="styles.css" rel="stylesheet">
<script defer src="script.js"></script>
</head>
<div class="container">
<div id="question-container" class="hide">
<div id="question">Question</div>
<div id="answer-buttons" class="btn-grid">
<button class="btn">Answer 1</button>
<button class="btn">Answer 2</button>
<button class="btn">Answer 3</button>
<button class="btn">Answer 4</button>
</div>
</div>
<div class="controls">
<button id="start-btn" class="start-btn btn">Start</button>
<button id="next-btn" class="next-btn btn hide">Next</button>
</div>
</div>
</html>
I added some quick fixes, try it.
const startButton = document.getElementById('start-btn')
const nextButton = document.getElementById('next-btn')
const submitButton = document.getElementById('submit')
const questionContainerElement = document.getElementById('question-container')
const questionElement = document.getElementById('question')
const answerButtonsElement = document.getElementById('answer-buttons')
const scoreText = document.getElementById("score");
let shuffledQuestions, currentQuestionIndex
let score = 0;
startButton.addEventListener('click', startGame)
nextButton.addEventListener('click', () => {
currentQuestionIndex++
setNextQuestion()
})
submitButton.addEventListener('click', showScore)
let executed = false;
function startGame() {
if (!executed) {
startButton.classList.add('hide')
shuffledQuestions = questions.sort(() => Math.random() - .5)
currentQuestionIndex = 0
questionContainerElement.classList.remove('hide')
setNextQuestion()
executed = true;
}
}
function setNextQuestion() {
resetState()
showQuestion(shuffledQuestions[currentQuestionIndex])
}
function showQuestion(question) {
questionElement.innerText = question.question
question.answers.forEach(answer => {
const button = document.createElement('button')
button.innerText = answer.text
button.classList.add('btn')
if (answer.correct) {
button.dataset.correct = answer.correct
}
button.addEventListener('click', function(e){
selectAnswer(e, answer);
}, false);
if (currentQuestionIndex < shuffledQuestions.length + 1) {
answerButtonsElement.appendChild(button)
}
})
}
function resetState() {
clearStatusClass(document.body)
nextButton.classList.add('hide')
while (answerButtonsElement.firstChild) {
answerButtonsElement.removeChild(answerButtonsElement.firstChild)
}
}
function selectAnswer(e, answer) {
const selectedButton = e.target
const correct = selectedButton.dataset.correct
setStatusClass(document.body, correct)
Array.from(answerButtonsElement.children).forEach(button => {
setStatusClass(button, button.dataset.correct)
})
if (answer.correct) {
score++;
}
if (shuffledQuestions.length > currentQuestionIndex + 1) {
nextButton.classList.remove('hide')
} else {
submitButton.classList.remove('hide')
}
}
function showScore () {
document.getElementById("score").innerHTML = "you got " + score + " correct.";
}
function setStatusClass(element, correct) {
clearStatusClass(element)
if (correct) {
element.classList.add('correct')
} else {
element.classList.add('wrong')
}
}
function clearStatusClass(element) {
element.classList.remove('correct')
element.classList.remove('wrong')
}
const questions = [{
question: 'What is the capital city of Brazil?',
answers: [{
text: 'Brasilia',
correct: true
},
{
text: 'Rio de Janeiro',
correct: false
}
]
},
{
question: 'What is the population of the United Kingdom in 2021?',
answers: [{
text: '68 million',
correct: true
},
{
text: '81 million',
correct: false
},
{
text: '56 million',
correct: false
},
{
text: '62 million',
correct: false
}
]
},
{
question: 'What country has the most people as of 2021?',
answers: [{
text: 'India',
correct: false
},
{
text: 'Indonesia',
correct: false
},
{
text: 'China',
correct: true
},
{
text: 'USA',
correct: false
}
]
},
{
question: 'Which city is bigger?',
answers: [{
text: 'Paris',
correct: false
},
{
text: 'London',
correct: true
}
]
},
{
question: 'What country is angkor wat in?',
answers: [{
text: 'Laos',
correct: false
},
{
text: 'Cambodia',
correct: true
},
{
text: 'Vietnam',
correct: false
},
{
text: 'Thailand',
correct: false
}
]
}
]
*, *::before, *::after {
box-sizing: border-box;
font-family: Gotham Rounded;
}
:root {
--hue-neutral: 200;
--hue-wrong: 0;
--hue-correct: 145;
}
body {
--hue: var(--hue-neutral);
padding: 0;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
justify-content: center;
align-items: center;
}
body.correct {
--hue: var(--hue-correct);
}
body.wrong {
--hue: var(--hue-wrong);
}
.container {
width: 600px;
max-width: 80%;
background-color: green;
border-radius: 5px;
padding: 10px;
box-shadow: 0 0 10px 2px;
color: white;
}
.btn-grid {
display: grid;
grid-template-columns: repeat(2, auto);
gap: 10px;
margin: 20px 0;
}
.btn {
--hue: var(--hue-neutral);
border: 1px solid hsl(var(--hue), 100%, 30%);
background-color: hsl(var(--hue), 100%, 50%);
border-radius: 5px;
padding: 5px 10px;
color: white;
outline: none;
}
.btn:hover {
border-color: black;
}
.btn.correct {
--hue: var(--hue-correct);
color: white;
}
.btn.wrong {
--hue: var(--hue-wrong);
}
.start-btn, .next-btn {
font-size: 1.5rem;
font-weight: bold;
padding: 10px 20px;
}
.controls {
display: flex;
justify-content: center;
align-items: center;
}
a {
text-decoration: solid;
color: white;
font-size: 300%
}
div.a {
position: absolute;
top: 0;
border: green;
}
.hide {
display: none;
}
#after_Submit {
visibility: hidden;
}
<html lang="en">
<title>Quiz App</title>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="styles.css" rel="stylesheet">
<script defer src="script.js"></script>
</head>
<div class="container">
<div id="question-container" class="hide">
<div id="question">Question</div>
<div id="answer-buttons" class="btn-grid">
<button class="btn">Answer 1</button>
<button class="btn">Answer 2</button>
<button class="btn">Answer 3</button>
<button class="btn">Answer 4</button>
</div>
</div>
<div class="controls">
<button id="start-btn" class="start-btn btn">Start</button>
<button id="next-btn" class="next-btn btn hide">Next</button>
<button id="submit" class="btn hide">Submit</button>
</div>
<div id="score"></div>
</div>
</html>

Why does classList.key == true not execute my if statement?

Using this code to create a simple math quiz. I have button's that are set string values for both the button's text and . The issue I'm currently, is having the setter properly the button's class value after evaluating it's key value.
Inside my setStatusClass. I used if's to check the object's key values for correct. I used debugger to see if the values were even being checked. And, they are. But, I'm understand the blocks aren't being ran.
// This document, when the start button is clicked, shows questions, & starts the timer
var startButton = document.getElementById("start-btn");
var questionContainerEl = document.getElementById("question-container");
var startScreen = document.getElementById("start-screen");
var questionTitle = document.getElementById("question");
var choiceButtons = document.getElementById("choice-buttons");
//var buttonVal = 0;
var score = 0;
var shuffleQuestions, currentQindex;
var i = 0;
//Object Container to hold questions and answers
const questions = [{
question: "What is 2 + 2?",
answers: [
{text: "4", correct: "true"},
{text: "2", correct: "false"},
{text: "3", correct: "false"},
{text: "5", correct: "false"}
]
},
{
question: "What is 4*4?",
answers: [{text: '8', correct: "false"},
{text: '16',correct: "true"},
{text: '2', correct: "false"},
{text: '6', correct: "false"},
]
},
{
question: "Solve for x. y = 3x - 6",
answers: [{text: '6', correct: "false"},
{text: '3', correct: "false"},
{text: '2', correct: "true"},
{text: "idk", correct: "false"}]
}];
startButton.addEventListener('click',startGame);
//Start game function shows Question Cont. Shuffles Questions on an Arr.
function startGame() {
startScreen.classList.add('hide');
shuffleQuestions = questions.sort(() => Math.random() - .5);
currentQindex = 0;
questionContainerEl.classList.remove('hide');
setNextQuestion();
}
//Erases question and finds next one on Arr.
function setNextQuestion() {
resetState();
showQuestion(shuffleQuestions[currentQindex]);
}
//Shows question as well as answers.
function showQuestion(questions){
questionTitle.innerText = questions.question;
var ansLength = Object.keys(questions.answers).length;
var ans;
for(i = 0; i < ansLength; i++) {
//When the answer button is selected questions goes to next object element
ans = questions.answers[i];
var button = document.createElement("button");
button.innerText = ans.text;
button.classList.add('btn');
if(ans.correct === "true") {
button.correct = ans.correct;
}
button.addEventListener("click", selectAnswer);
choiceButtons.appendChild(button);
}
}
//removes buttons from choices.
function resetState() {
while(choiceButtons.firstChild) {
choiceButtons.removeChild(choiceButtons.firstChild);
}
}
function selectAnswer(e) {
//setStatusClass(document.body, isCorrect);
var ar = Array.from(choiceButtons.children);
for (buttons of ar) {
var selectedButton = e.target;
var isCorrect = selectedButton.dataset.correct;
setStatusClass(buttons, isCorrect);
}
}
function setStatusClass(element) {
clearStatusClass(element);
if (element.classList.correct == "true") {
element.classList.add("right");
}
if (element.classList.correct == "false") {
element.classList.add("incorrect");
}
}
function clearStatusClass(element){
element.classList.remove("right");
element.classList.remove("incorrect");
}
*, *::before, *::after {
box-sizing: border-box;
font-family: "Comic Sans MS", cursive, sans-serif;
font-weight: 500;
}
body {
padding: 0;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
justify-content: center;
align-items: center;
background-color: #b3d7ff;
}
.start-screen {
display:flex;
justify-content: center;
align-items: center;
}
.start-btn {
font-size: 1.5rem;
font-weight: bold;
padding: 10px 20px;
}
.btn-grid {
display: grid;
grid-template-columns: repeat(2,auto);
}
.btn {
border: black;
background-color: #b3d7ff;
border-radius: 10px;
padding: 5px 10px;
color: white;
outline: dashed;
margin: 5px;
}
.btn.right {
background-color: lightgreen;
color:black
}
.btn.incorrect {
background-color: red;
color:black;
}
.btn:hover{
border-color: black;
}
.wrapper {
width: 800px;
max-width: 80%;
background-color: white;
border-radius: 5px;
padding: 10px;
box-shadow: 0 0 10px 2px;
}
.scores {
float:left;
align-self: flex-start;
position: absolute;
}
.timer {
float:left;
align-self: flex-start;
}
.container {
width: 800px;
max-width: 80%;
background-color: white;
border-radius: 5px;
padding: 10px;
box-shadow: 0 0 10px 2px;
}
.hide {
display: none;
}
#question {
width: 700px;
max-width: 80%;
padding: 5px;
border: 2px;
text-align: center;
margin-top: 5px;
margin-bottom: 2px;
margin-left: 75px;
margin-right: 75px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge" />
<title>The Quiz</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="./Assets/css/style.css" type = "text/css" media= "screen">
</head>
<body>
<div class="scores">View Highscores</div>
<div class="timer">Time: <span id="time">0</span></div>
<div class="wrapper">
<div id="start-screen" class="start">
<h1>The Quiz</h1>
<p>
This quiz is on a timer. Please do your best to complete it before the timer runs out.
Keep in mind that wrong answers will penalize you.
</p>
<button id="start-btn" class = "start-btn btn?">Start the Quiz</button>
</div>
<div id= "question-container" class= "hide">
<div id="question">Question</div>
<div id="choice-buttons" class= "btn-grid">
<button class= "btn hover">Answer 1</button>
<button class= "btn hover">Answer 2</button>
<button class= "btn hover">Answer 3</button>
<button class= "btn hover">Answer 4</button>
</div>
</div>
<div id="final-screen" class= "hide">
<h2>You're finished</h2>
<p>Your final score is<span id="final-score"></span>.</p>
<p>
Enter intials: <input type="text" id="initals" max="3" />
<button id="submit">Submit</button>
</p>
</div>
</div>
<script defer src="./Assets/js/logic.js"></script>
<script defer src="./Assets/js/questions.js"></script>
</body>
</html>
The way to tell if a class is in an element's class list is with the .includes() method.
function setStatusClass(element) {
clearStatusClass(element);
if (element.classList.includes("correct")) {
element.classList.add("right");
} else {
element.classList.add("incorrect");
}
}

How can i turn a card in this game to its original position IF is wrong?

var cards = [
{
rank: "Queen",
suit: "Hearts",
cardImage: "images/queen-of-hearts.png",
id: 0,
},
{
rank: "Queen",
suit: "Diamonds",
cardImage: "images/queen-of-diamonds.png",
id: 1,
},
{
rank: "King",
suit: "Hearts",
cardImage: "images/king-of-hearts.png",
id: 2,
},
{
rank: "King",
suit: "Diamonds",
cardImage: "images/king-of-diamonds.png",
id: 3
}
];
//1
function createBoard() {
for (var i = 0; i < cards.length; i++) {
var cardElement = document.createElement('img');
// console.log(cardElement);
cardElement.setAttribute('src', 'images/back.png');
cardElement.setAttribute('data-id', i);
document.getElementById('game-board').appendChild(cardElement);
cardElement.addEventListener('click', flipCard);
cardElement.style.width = '210px';
}
}
createBoard();
//2
function flipCard () {
var cardId = this.getAttribute('data-id');
cardsInPlay.push(cards[cardId].rank);
cardsInPlay.push(cards[cardId].id);
this.setAttribute('src', cards[cardId].cardImage);
// CHECK FOR MATCH HERE =>
if (cardsInPlay.length === 2) {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
}
else {
alert("Sorry, try again.");
console.log(cardsInPlay);
cardsInPlay[0].setAttribute('src', 'images/back.png'); // this doesnt work
cardsInPlay[1].setAttribute('src', 'images/back.png'); // this doesnt work
}
}
}
var cardsInPlay = [];
body{
text-align: center;
margin: 0;
}
h1 {
font-family: "Raleway", sans-serif;
font-weight: 400;
color: #0d2c40;
font-size: 45px;
letter-spacing: 1px;
margin: 0;
color: white;
}
p {
font-family: "Droid Serif", serif;
line-height: 26px;
font-size: 18px;
}
a {
font-family: raleway;
text-decoration: none;
color: #F15B31;
letter-spacing: 1px;
font-weight: 600;
font-size: 18px;
}
h2 {
font-family: raleway;
font-size: 20px;
color: #0d2c40;
letter-spacing: 1px;
font-weight: 600;
}
header {
background-color: #F15B31;
padding: 30px 20px 30px 20px;
}
main {
width: 850px;
margin: 35px auto
}
a {
margin: 0 20px;
color: white;
}
nav a:hover {
border-bottom: 2px solid white;
}
nav {
background-color: #00A6B3;
padding: 20px 0;
}
img {
margin: 40px 8px 0 8px;
}
footer {
text-transform: uppercase;
padding: 0 20px;
background-color: #0D2C40;
color: white;
letter-spacing: .08em;
font-weight: 500;
}
.copyright {
float: left;
}
.message {
float: right;
}
.clearfix:after {
visibility: hidden;
display: block;
content: " ";
clear: both;
height: 0;
font-size: 0;
}
.name {
color: #F15B31;
font-weight: 700;
}
#game-board{
width: 1200px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet" type="text/css">
<title>Memory card game</title>
</head>
<body>
<header>
<h1>Memory Game</h1>
</header>
<nav>
<p>INSTRUCTIONS GAME</p>
</nav>
<main>
<h2>INSTRUCTIONS</h2>
<p>Concentration, also known as Match Match, Memory, Pelmanism, Shinkei-suijaku, Pexeso or simply Pairs, is a card game in which all of the cards are laid face down on a surface and two cards are flipped face up over each turn. The object of the game is to turn over pairs of matching cards.</p>
<div id="game-board" class="board clearfix"></div>
</main>
<footer>
<div class="clearfix">
<p class="copyright">Copyright 2017</p>
<p class="message">Created with ♥ by <span class="name">GA</span></p>
</div>
</footer>
<script src="js/main.js"></script>
</body>
</html>
I want to know how I can turn back to its original position BOTH cards that didn't match. If there is a match, there is an alert saying congrats you win, OTHERWISE try again, but i want that two cards to return to its original position if didnt match. BUT ONLY ONE CARD TURN BACK TO ITS ORIGINAL POSITION(the one with the this , but I thought the this refers to both) The card images are not in here. Can someone help with this please?
var cards = [
{
rank: "Queen",
suit: "Hearts",
cardImage: "images/queen-of-hearts.png",
id: 0,
},
{
rank: "Queen",
suit: "Diamonds",
cardImage: "images/queen-of-diamonds.png",
id: 1,
},
{
rank: "King",
suit: "Hearts",
cardImage: "images/king-of-hearts.png",
id: 2,
},
{
rank: "King",
suit: "Diamonds",
cardImage: "images/king-of-diamonds.png",
id: 3
}
];
//1
function createBoard() {
for (var i = 0; i < cards.length; i++) {
var cardElement = document.createElement('img');
// console.log(cardElement);
cardElement.setAttribute('src', 'images/back.png');
cardElement.setAttribute('data-id', i);
document.getElementById('game-board').appendChild(cardElement);
cardElement.addEventListener('click', flipCard);
cardElement.style.width = '210px';
}
}
createBoard();
//2
function flipCard () {
var cardId = this.getAttribute('data-id');
cardsInPlay.push(cards[cardId].rank);
cardsInPlay.push(cards[cardId].id);
this.setAttribute('src', cards[cardId].cardImage);
// CHECK FOR MATCH HERE =>
if (cardsInPlay.length === 2) {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
}
else {
alert("Sorry, try again.");
console.log(cardsInPlay);
cardsInPlay[0].setAttribute('src', 'images/back.png'); // this doesnt work
cardsInPlay[1].setAttribute('src', 'images/back.png'); // this doesnt work
}
}
}
var cardsInPlay = [];
body{
text-align: center;
margin: 0;
}
h1 {
font-family: "Raleway", sans-serif;
font-weight: 400;
color: #0d2c40;
font-size: 45px;
letter-spacing: 1px;
margin: 0;
color: white;
}
p {
font-family: "Droid Serif", serif;
line-height: 26px;
font-size: 18px;
}
a {
font-family: raleway;
text-decoration: none;
color: #F15B31;
letter-spacing: 1px;
font-weight: 600;
font-size: 18px;
}
h2 {
font-family: raleway;
font-size: 20px;
color: #0d2c40;
letter-spacing: 1px;
font-weight: 600;
}
header {
background-color: #F15B31;
padding: 30px 20px 30px 20px;
}
main {
width: 850px;
margin: 35px auto
}
a {
margin: 0 20px;
color: white;
}
nav a:hover {
border-bottom: 2px solid white;
}
nav {
background-color: #00A6B3;
padding: 20px 0;
}
img {
margin: 40px 8px 0 8px;
}
footer {
text-transform: uppercase;
padding: 0 20px;
background-color: #0D2C40;
color: white;
letter-spacing: .08em;
font-weight: 500;
}
.copyright {
float: left;
}
.message {
float: right;
}
.clearfix:after {
visibility: hidden;
display: block;
content: " ";
clear: both;
height: 0;
font-size: 0;
}
.name {
color: #F15B31;
font-weight: 700;
}
#game-board{
width: 1200px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet" type="text/css">
<title>Memory card game</title>
</head>
<body>
<header>
<h1>Memory Game</h1>
</header>
<nav>
<p>INSTRUCTIONS GAME</p>
</nav>
<main>
<h2>INSTRUCTIONS</h2>
<p>Concentration, also known as Match Match, Memory, Pelmanism, Shinkei-suijaku, Pexeso or simply Pairs, is a card game in which all of the cards are laid face down on a surface and two cards are flipped face up over each turn. The object of the game is to turn over pairs of matching cards.</p>
<div id="game-board" class="board clearfix"></div>
</main>
<footer>
<div class="clearfix">
<p class="copyright">Copyright 2017</p>
<p class="message">Created with ♥ by <span class="name">GA</span></p>
</div>
</footer>
<script src="js/main.js"></script>
</body>
</html>
If you are trying to flip both cards back, this code only flips the last card in play "cardsInPlay[1]":
this.setAttribute('src', 'images/back.png');
What you want is to flip both "cardsInPlay[0]" and "cardsInPlay[1]" so maybe somethign like this:
else {
alert("Sorry, try again.");
console.log(cardsInPlay);
cardsInPlay[0].setAttribute('src', 'images/back.png');
cardsInPlay[1].setAttribute('src', 'images/back.png');
}
EDIT: your problem with this is about closure in javascript. I recommend you use IIFE (for EcmaScript5) or let keyword (for EcmaScript6). Read more here.
Instead of doing this:
function createBoard() {
for (var i = 0; i < cards.length; i++) {
var cardElement = document.createElement('img');
[..]
cardElement.addEventListener('click', flipCard); << 'this' will refer to last cardElement at the end of the loop
Do this:
function createBoard() {
for (var i = 0; i < cards.length; i++) {
var cardElement = document.createElement('img');
[..]
cardElement.addEventListener('click', (function(x) {return function() {flipCard(x)}})(i)); // 'i' is immediately evaluated to the correct value
cards[i].element = cardElement; // Keep association with DOM here
Now you can flip cards back easily.
function flipCard (i) {
cardsInPlay.push(i);
// Flip played card
cards[i].element.setAttribute('src', cards[i].cardImage);
if (cardsInPlay.length === 1)
return; // First card: no game resolution yet
// Second card: give user 1s to see it flipped before flipping back
setTimeout(function(){
if (cards[cardsInPlay[0]].rank === cards[cardsInPlay[1]].rank)
alert("You found a match!");
else
alert("Sorry, try again.");
cardsInPlay.forEach(function(i) {
cards[i].element.setAttribute('src', 'images/back.png');
});
cardsInPlay.length = 0;
}, 1000);
}
The below snippet is modified to achieve the required functionality! can you please check?
var cards = [
{
rank: "Queen",
suit: "Hearts",
cardImage: "http://via.placeholder.com/350x150?text=QueenHeartsfront"
},
{
rank: "Queen",
suit: "Diamonds",
cardImage: "http://via.placeholder.com/350x150?text=QueenDiamondsfront"
},
{
rank: "King",
suit: "Hearts",
cardImage: "http://via.placeholder.com/350x150?text=KingHeartsfront"
},
{
rank: "King",
suit: "Diamonds",
cardImage: "http://via.placeholder.com/350x150?text=KingDiamondsfront"
}
];
//1 CREATE BOARD
function createBoard() {
for (var i = 0; i < cards.length; i++) {
var cardElement = document.createElement('img');
// console.log(cardElement);
cardElement.setAttribute('src', 'http://via.placeholder.com/350x150?text=back');
cardElement.setAttribute('data-id', i);
document.getElementById('game-board').appendChild(cardElement);
cardElement.addEventListener('click', flipCard);
cardElement.style.width = '210px';
}
}
createBoard();
var prev = "";
//2 FLIPCARD
function flipCard () {
var cardId = this.getAttribute('data-id');
cardsInPlay.push(cards[cardId].rank);
this.setAttribute('src', cards[cardId].cardImage);
console.log(cardsInPlay[0]);
console.log(cardsInPlay[1]);
if (cardsInPlay.length === 2) {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
cardsInPlay = [];
}
else {
alert("Sorry, try again.");
cardsInPlay = [];
// cardsInPlay.pop();
// cardsInPlay.pop();
// console.log(cardsInPlay);
try{
prev.setAttribute('src', 'http://via.placeholder.com/350x150?text=back');
}catch(e){}
this.setAttribute('src', 'http://via.placeholder.com/350x150?text=back');
}
}
prev = this;
}
var cardsInPlay = [];
body{
text-align: center;
margin: 0;
}
h1 {
font-family: "Raleway", sans-serif;
font-weight: 400;
color: #0d2c40;
font-size: 45px;
letter-spacing: 1px;
margin: 0;
color: white;
}
p {
font-family: "Droid Serif", serif;
line-height: 26px;
font-size: 18px;
}
a {
font-family: raleway;
text-decoration: none;
color: #F15B31;
letter-spacing: 1px;
font-weight: 600;
font-size: 18px;
}
h2 {
font-family: raleway;
font-size: 20px;
color: #0d2c40;
letter-spacing: 1px;
font-weight: 600;
}
header {
background-color: #F15B31;
padding: 30px 20px 30px 20px;
}
main {
width: 850px;
margin: 35px auto
}
a {
margin: 0 20px;
color: white;
}
nav a:hover {
border-bottom: 2px solid white;
}
nav {
background-color: #00A6B3;
padding: 20px 0;
}
img {
margin: 40px 8px 0 8px;
}
footer {
text-transform: uppercase;
padding: 0 20px;
background-color: #0D2C40;
color: white;
letter-spacing: .08em;
font-weight: 500;
}
.copyright {
float: left;
}
.message {
float: right;
}
.clearfix:after {
visibility: hidden;
display: block;
content: " ";
clear: both;
height: 0;
font-size: 0;
}
.name {
color: #F15B31;
font-weight: 700;
}
#game-board{
width: 1200px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet" type="text/css">
<title>Memory card game</title>
</head>
<body>
<header>
<h1>Memory Game</h1>
</header>
<nav>
<p>INSTRUCTIONS GAME</p>
</nav>
<main>
<h2>INSTRUCTIONS</h2>
<p>Concentration, also known as Match Match, Memory, Pelmanism, Shinkei-suijaku, Pexeso or simply Pairs, is a card game in which all of the cards are laid face down on a surface and two cards are flipped face up over each turn. The object of the game is to turn over pairs of matching cards.</p>
<div id="game-board" class="board clearfix"></div>
</main>
<footer>
<div class="clearfix">
<p class="copyright">Copyright 2017</p>
<p class="message">Created with ♥ by <span class="name">GA</span></p>
</div>
</footer>
<script src="js/main.js"></script>
</body>
</html>

Categories