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

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()

Related

Javascript Won't replace image

My Js code below is a quiz game. Each question takes up a full page, which means we have to change all the content every time the user presses the next button.
My issue is, i can't seem to get the image to switch to the next by fully replacing it. In my case the new images just go to the bottom of the first.
// Questions will be asked//
const Questions = [
{ id: 0, i: "images/trump.jpg", a: [{ text: "George Washington", isCorrect: false }, { text: "John Adams", isCorrect: false }, { text: "James Madison", isCorrect: false }, { text: "Donald John Trump", isCorrect: true } ] },
{ id: 1, i: "http://www.google.com/intl/en_com/images/logo_plain.png", a: [{ text: "Lampang", isCorrect: false, isSelected: false }, { text: "phuket", isCorrect: false }, { text: "Ayutthaya", isCorrect: false }, { text: "Bangkok", isCorrect: true } ] },
{ id: 2, i: "http://www.google.com/intl/en_com/images/logo_plain.png", a: [{ text: "surat", isCorrect: false }, { text: "vadodara", isCorrect: false }, { text: "gandhinagar", isCorrect: true }, { text: "rajkot", isCorrect: false } ] }
]
// Set start//
var start = true;
// Iterate//
function iterate(id) {
// Getting the result display section//
var result = document.getElementsByClassName("result");
result[0].innerText = "";
//Adding an image//
var img = document.createElement("img");
img.src = Questions[id].i;
var src = document.getElementById("image");
src.appendChild(img);
// Getting the options//
const op1 = document.getElementById('op1');
const op2 = document.getElementById('op2');
const op3 = document.getElementById('op3');
const op4 = document.getElementById('op4');
// Providing option text//
op1.innerText = Questions[id].a[0].text;
op2.innerText = Questions[id].a[1].text;
op3.innerText = Questions[id].a[2].text;
op4.innerText = Questions[id].a[3].text;
// Providing the true or false value to the options//
op1.value = Questions[id].a[0].isCorrect;
op2.value = Questions[id].a[1].isCorrect;
op3.value = Questions[id].a[2].isCorrect;
op4.value = Questions[id].a[3].isCorrect;
var selected = "";
// Show selection for op1//
op1.addEventListener("click", () => {
op1.style.backgroundColor = "lightgoldenrodyellow";
op2.style.backgroundColor = "lightskyblue";
op3.style.backgroundColor = "lightskyblue";
op4.style.backgroundColor = "lightskyblue";
selected = op1.value;
})
// Show selection for op2//
op2.addEventListener("click", () => {
op1.style.backgroundColor = "lightskyblue";
op2.style.backgroundColor = "lightgoldenrodyellow";
op3.style.backgroundColor = "lightskyblue";
op4.style.backgroundColor = "lightskyblue";
selected = op2.value;
})
// Show selection for op3//
op3.addEventListener("click", () => {
op1.style.backgroundColor = "lightskyblue";
op2.style.backgroundColor = "lightskyblue";
op3.style.backgroundColor = "lightgoldenrodyellow";
op4.style.backgroundColor = "lightskyblue";
selected = op3.value;
})
// Show selection for op4//
op4.addEventListener("click", () => {
op1.style.backgroundColor = "lightskyblue";
op2.style.backgroundColor = "lightskyblue";
op3.style.backgroundColor = "lightskyblue";
op4.style.backgroundColor = "lightgoldenrodyellow";
selected = op4.value;
})
// Grabbing the evaluate button//
const evaluate = document.getElementsByClassName("evaluate");
// Evaluate method//
evaluate[0].addEventListener("click", () => {
if (selected == "true") {
result[0].innerHTML = "True";
result[0].style.color = "green";
} else {
result[0].innerHTML = "False";
result[0].style.color = "red";
}
})
}
if (start) {
iterate("0");
}
// Next button and method//
const next = document.getElementsByClassName('next')[0];
var id = 0;
next.addEventListener("click", () => {
setTimeout(() => {
start = false;
if (id < 2) {
id++;
iterate(id);
console.log(id);
}
})
})
:root {
--primary: #1D1D1F;
--secondary: #858786;
--erro: #FF5757;
text-align: center;
align-items: center;
align-self: center;
font-family: SF Pro Display, SF Pro Icons, AOS Icons, Helvetica Neue, Helvetica, Arial, sans-serif;
}
.column {
justify-items: center;
justify-content: center;
float: left;
width: 50%;
justify-content: center;
}
.main-container {
margin: 50px;
border-radius: 20px;
background-color: #F5F8FA;
}
/* Clear floats after the columns */
.main-container:after {
content: "";
display: table;
clear: both;
}
.main-container img {
width: 320px;
height: 320px;
border-radius: 20px;
object-position: center;
object-fit: cover;
}
.center-cropped img {
border-radius: 2px;
width: 50%;
height: 50%;
object-position: center;
object-fit: cover;
}
.option-container {
margin-top: 50%;
margin-bottom: 50%;
grid-column: 1;
margin: 10px;
padding: 5px;
width: 100%;
height: auto;
}
.quiz-image {
margin: 10px;
padding: 10px;
width: 100%;
}
.bottom-left {
position: absolute;
bottom: 8px;
left: 16px;
}
.option {
border-radius: 10px;
border-width: 0px;
margin: 10px;
padding: 10px;
width: 50%;
height: auto;
font-size: 1rem;
font-weight: 600;
color: white;
background-color: #1da1f2;
}
.option:hover {
background-color: #e1e8ed;
}
.title h1 {
font-size: 4rem;
font-weight: 400;
padding: 10px;
color: #1d1d1d;
}
.title h2 {
font-size: 1.5rem;
font-weight: 400;
color: #1D1D1D;
}
h2 {
font-size: 3rem;
font-weight: 300;
color: #1D1D1D;
}
.question-container {
margin: 10px;
padding: 5px;
width: 80vw;
height: 10vh;
background-color: #c7dddf;
font-size: x-large;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">
<h1>Guess The President</h1>
</div>
<div class="main-container" >
<div class="result"></div>
<div class="column">
<div class="quiz-image" id="image"></div>
</div>
<div class="column">
<div class="option-container">
<button class="option" onclick="" id="op1">option1</button>
<button class="option" id="op2">option2</button>
<button class="option" id="op3">option3</button>
<button class="option" id="op4">option4</button>
</div>
</div>
</div>
<div class="navigation">
<button class="evaluate">Evaluate</button>
<button class="next">Next</button>
</div>
Where you have your
src.appendChild(img);
Change it to this:
src.innerHTML = "";
src.appendChild(img);
This will clear out the previous image and the new one will be added in.
Hope this helps.
Just for the heck of it. Not really an answer, but thought your question used jQuery but your code did not use it (sorry, Andy, it's a mess!). The following code is dynamic and will adapt to how many questions you have, each may contain a varying amount of different answers.
// Questions will be asked//
const questions = [
{ id: 0, i: "https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Donald_Trump_official_portrait.jpg/330px-Donald_Trump_official_portrait.jpg", a: [{ text: "George Washington", isCorrect: false }, { text: "John Adams", isCorrect: false }, { text: "James Madison", isCorrect: false }, { text: "Donald John Trump", isCorrect: true } ] },
{ id: 1, i: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Bangkok_Montage_2021.jpg/375px-Bangkok_Montage_2021.jpg", a: [{ text: "Lampang", isCorrect: false, isSelected: false }, { text: "phuket", isCorrect: false }, { text: "Ayutthaya", isCorrect: false }, { text: "Bangkok", isCorrect: true } ] },
{ id: 2, i: "https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Akshardham_Gandhinagar_Gujarat.jpg/405px-Akshardham_Gandhinagar_Gujarat.jpg", a: [{ text: "surat", isCorrect: false }, { text: "vadodara", isCorrect: false }, { text: "gandhinagar", isCorrect: true }, { text: "rajkot", isCorrect: false } ] }
];
// Set start//
const game = {
active: true,
currentQuestion: 0,
selectedAnswer: null,
evaluated: false,
score: 0
};
function updateAnswerStatus() {
const progressText = `${game.currentQuestion + 1} / ${questions.length} - ${game.score} pts`;
const hasNext = game.currentQuestion < questions.length - 1;
$('#result').text(progressText);
$('#btnEvaluate').attr('disabled', game.evaluated || !game.selectedAnswer);
$('#btnNext').attr('disabled', !game.evaluated || !hasNext);
}
function selectAnswer(selectedAnswer) {
if (!game.evaluated) {
game.selectedAnswer = selectedAnswer;
$('#optionList .option').each(function () {
const option = $(this);
const answer = option.data('answer');
if (answer === selectedAnswer) {
option.addClass('selected');
} else {
option.removeClass('selected');
}
});
updateAnswerStatus()
}
}
function evaluateAnswer() {
if (!game.evaluated && game.selectedAnswer) {
game.evaluated = true;
$('#optionList .option').each(function () {
const option = $(this);
const answer = option.data('answer');
if (answer === game.selectedAnswer) {
option.addClass( answer.isCorrect ? 'correct' : 'incorrect');
game.score = game.score + (answer.isCorrect ? 1 : 0);
}
});
updateAnswerStatus();
}
}
function createOption(answer) {
return $('<button>')
.data({ answer })
.text(answer.text)
.addClass('option')
.on('click', function() {
selectAnswer(answer);
})
;
}
function renderCurrentQuestion() {
const question = questions[game.currentQuestion];
if (question) {
const optList = $('#optionList').empty();
const image = $('#image').empty();
game.selectedAnswer = null;
game.evaluated = false;
image.append($('<img>').attr('src', question.i));
for (const answer of question.a) {
optList.append( createOption(answer) );
}
}
updateAnswerStatus();
};
// next question?
$('#btnNext').on('click', function() {
game.currentQuestion = game.currentQuestion + 1;
renderCurrentQuestion();
}).attr('disabled', true);
$('#btnEvaluate').on('click', function() {
evaluateAnswer();
});
if (game.active) {
renderCurrentQuestion();
}
:root {
--primary: #1D1D1F;
--secondary: #858786;
--erro: #FF5757;
text-align: center;
align-items: center;
align-self: center;
font-family: SF Pro Display, SF Pro Icons, AOS Icons, Helvetica Neue, Helvetica, Arial, sans-serif;
}
.column {
justify-items: center;
justify-content: center;
float: left;
width: 50%;
justify-content: center;
}
.main-container {
margin: 50px;
border-radius: 20px;
background-color: #F5F8FA;
}
/* Clear floats after the columns */
.main-container:after {
content: "";
display: table;
clear: both;
}
.main-container img {
width: 320px;
height: 320px;
border-radius: 20px;
object-position: center;
object-fit: cover;
}
.center-cropped img {
border-radius: 2px;
width: 50%;
height: 50%;
object-position: center;
object-fit: cover;
}
.option-container {
margin-top: 50%;
margin-bottom: 50%;
grid-column: 1;
margin: 10px;
padding: 5px;
width: 100%;
height: auto;
}
.quiz-image {
margin: 10px;
padding: 10px;
width: 100%;
}
.bottom-left {
position: absolute;
bottom: 8px;
left: 16px;
}
.option {
border-radius: 10px;
border-width: 0px;
margin: 10px;
padding: 10px;
width: 50%;
height: auto;
font-size: 1rem;
font-weight: 600;
color: white;
background-color: #1da1f2;
}
.option:hover {
color: #1da1f2;
background-color: #d1d8dd;
}
.option.selected {
background-color: #bbbb33;
}
.option.selected:hover {
color: white;
background-color: #777733;
}
.option.selected.incorrect {
background-color: #bb3333;
}
.option.selected.correct {
background-color: #33bb33;
}
.title h1 {
font-size: 4rem;
font-weight: 400;
padding: 10px;
color: #1d1d1d;
}
.title h2 {
font-size: 1.5rem;
font-weight: 400;
color: #1D1D1D;
}
h2 {
font-size: 3rem;
font-weight: 300;
color: #1D1D1D;
}
.question-container {
margin: 10px;
padding: 5px;
width: 80vw;
height: 10vh;
background-color: #c7dddf;
font-size: x-large;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">
<h1>Guess the answer</h1>
</div>
<div class="main-container" >
<div id="result" class="result"></div>
<div class="column">
<div id="image"class="quiz-image"></div>
</div>
<div class="column">
<div id="optionList" class="option-container"></div>
</div>
</div>
<div class="navigation">
<button id="btnEvaluate" class="evaluate">Evaluate</button>
<button id="btnNext" class="next">Next</button>
</div>

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 prevent users from selecting multiple answers in my quiz?

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);

chrome doesn't display innerHTML changes

I am creating a game of Boggle using an external javascript page to create the arrays. The problem I am having is
Chrome doesn't display the letters without creating a button to display them separately.
As the user enters words, the words are not displaying until the user quits the game.
It works fine on Firefox but I want it to work in Chrome too.
Any suggestions?
function words(x) {
switch (x) {
case 1:
var word = new Array("balte", "table", "hat", "tab", "belt", "lab", "eat", "tea", "ate", "tale", "bale", "let", "bet", "teal", "late", "beat");
break;
case 2:
var word = new Array("atwre", "water", "wet", "wear", "tear", "war", "ret", "rate", "eat", "ate", "tea", "awe", "raw", "rat", "wart", "art", "tar");
break;
case 3:
var word = new Array("dclaen", "can", "cane", "and", "clan", "lane", "lean", "lend", "land", "den", "dean", "dance", "lance", "clean", "deal", "ale", "dale", "candle", "clad");
break;
case 4:
var word = new Array("aepinlar", "air", "airplane", "plane", "plan", "lane", "lean", "pane", "ear", "near", "nap", "nape", "lair", "pen", "pan", "ape", "leap", "ale", "peal", "nap", "rap", "par", "pare", "pale", "are", "rail", "ail", "pail", "nail", "air", "pair", "ran", "pin", "pine", "line", "nip", "rip", "ripe", "lip", "earn", "learn", "ire");
break;
case 5:
var word = new Array("redykboa", "keyboard", "key", "board", "bored", "bore", "bark", "dark", "dork", "oar", "boar", "ark", "dare", "bare", "are", "red", "rod", "road", "bode", "rode", "ode", "bread", "read", "bead", "bred", "break", "drey", "day", "boy", "broke", "rake", "bake", "ear", "dear", "bear", "dye", "dyer", "doer", "oak", "boa", "doe", "okay", "dab", "bade", "ade", "drake", "bard", "yard", "year", "beak", "beard", "bad", "bed", "bay");
break;
}
return word;
}
compWords = new Array();
notAword = new Array();
playWords = new Array();
function displayLetters() {
var num = Math.floor(Math.random() * 5) + 1;
compWords = words(num);
yourWord = compWords[0];
document.getElementById("letters").innerHTML = yourWord;
}
function displayEntries() {
document.getElementById("entries").innerHTML = playWords.toString();
}
function boggle() {
var play = "";
var score = 0;
var flag = 0;
//get player entries
while (play != "Q") {
play = prompt("enter a word or enter Q when done");
playWords.push(play);
if (play != "Q")
//document.getElementById("entries").innerHTML = playWords.toString();
displayEntries();
}
// check winning score and list bad words
var complgth = compWords.length;
var playlgth = (playWords.length - 1);
for (var i = 0; i < playlgth; i++) {
flag = 0;
for (var k = 0; k < complgth; k++) {
if (playWords[i] == compWords[k]) {
score++;
flag = 1;
}
}
if (flag == 0)
notAword.push(playWords[i]);
}
document.getElementById("result").innerHTML = ("Your score is " +
score + ". The following entries " +
"are not valid words: <br />" +
notAword.toString());
}
body {
background-color: #000040;
color: #88ffff;
font-family: Verdana, Arial, sans-serif;
}
#container {
margin-left: auto;
margin-right: auto;
width: 80%;
min-width: 700px;
}
#logo {
text-align: center;
margin: 0;
font-family: Geneva, Arial, Helvetica, sans-serif;
padding-top: 30px;
padding-bottom: 20px;
}
#nav {
float: left;
width: 200px;
padding-top: 10px;
text-align: left;
color: #88FFFF;
font-size: 12px;
}
#nav a {
text-decoration: none;
margin: 15px;
display: block;
color: #88FFFF;
font-size: 12px;
}
#content {
margin-left: 150px;
padding: 30px;
overflow: auto;
border: medium groove #88FFFF;
line-height: 135%;
}
.floatright {
padding-left: 20px;
float: right;
}
.floatleft {
float: left;
padding: 30px 0px 20px;
}
#footer {
font-size: .60em;
font-style: italic;
text-align: center;
border-top: 2px double #000040;
padding-top: 20px;
padding-bottom: 20px;
}
h2 {
text-transform: uppercase;
color: #88ffff;
font-size: 1.2em;
border-bottom: 1px none;
margin-right: 20px;
}
h3 {
color: #88ffff;
font-size: 1.2em;
border-bottom: 1px solid #000000;
margin-right: auto;
text-align: left;
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
line-height: 120%;
}
.details {
padding-left: 20%;
padding-right: 20%;
}
img {
border: 0;
}
.content {
margin: 20px;
padding: 20px;
height: 3700px;
width: 500px;
}
a {
text-decoration: none;
margin: 15px;
display: block;
color: #88FFFF;
font-size: 12px;
}
a:hover {
color: #000040;
background-color: #88ffff;
}
span {
font-size: 20px;
font-weight: bold;
font-family: "Courier New", Courier, mono;
color: #88ffff;
background-position: center center;
text-align: center;
vertical-align: middle;
}
table {
border-collapse: collapse
}
td {
border: 2px solid #88ffff;
width: 5em;
color: #88ffff;
}
.nobdr {
border: none;
cell-padding: 5px;
}
.OK {
border-radius: 50%;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Greg's Gambits | Greg's Game of Boggle</title>
<link href="greg.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="gregBoggle.js"></script>
<script>
</script>
</head>
<body>
<div id="container">
<img src="images/superhero.jpg" width="120" height="120" class="floatleft" />
<h1 align="center"><em>Greg's Game of Boggle</em></h1>
<div style="clear:both;"></div>
<div id="nav">
<p>Home
About
Play a Game
Sign In
Contact Us</p>
</div>
<div id="content">
<p>The object of the game is to create as many words as you can, in a given time limit, from the letters show below. When you are ready to begin, click the Diplay letters button, then Begin game button.</p>
<p><input type="button" value="Display letters" onclick="displayLetters();" /></p>
<p><input type="button" value="Begin the game" onclick="boggle();" /></p>
<h2><br /><br />Letters you can use:<br />
<div id="letters"> </div><br /></h2>
<h2>Your words so far: <br />
<div id="entries"> </div><br /></h2>
<h2>Results:<br />
<div id="result"> </div>
</h2>
</div>
<div id="footer">Copyright © 2013 Greg's Gambits<br />
foulksy#gmail.com
</div>
</div>
</body>
</html>
Browsers aren't required to render DOM changes until the script finishes and returns to the main event loop. Firefox also does this when you call prompt(), but I don't think this is required.
Instead of using a while loop, you should use an input element that the user fills in. You can then use an event listener to read the input and update the DOM. This will work in all browsers.

Answering bot title position & send button not working

Before I ask my questions, let me show you the full code for the project I'm working on (I'm making a bot that answers questions given some key words. It's a very easy code developed by Deni Spasovski).
This is the main HTML file:
<html>
<head>
<script type="text/javascript" src="chat.js"></script>
<style>
* {
box-sizing: border-box;
}
body {
background-color: #edeff2;
font-family: "Calibri", "Roboto", sans-serif;
}
.chat_window {
position: absolute;
width: calc(100% - 20px);
max-width: 800px;
height: 500px;
border-radius: 10px;
background-color: #fff;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
background-color: #ffffff;
overflow: hidden;
}
.top_menu {
background-color: #fff;
width: 100%;
padding: 20px 0 15px;
box-shadow: 0 1px 30px rgba(0, 0, 0, 0.1);
}
.top_menu .buttons {
margin: 3px 0 0 20px;
position: absolute;
}
.top_menu .buttons .button {
width: 16px;
height: 16px;
border-radius: 50%;
display: inline-block;
margin-right: 10px;
position: relative;
}
.top_menu .buttons .button.close {
background-color: #f5886e;
}
.top_menu .buttons .button.minimize {
background-color: #fdbf68;
}
.top_menu .buttons .button.maximize {
background-color: #a3d063;
}
.top_menu .title {
text-align: center;
color: #bcbdc0;
font-size: 20px;
}
.messages {
position: relative;
list-style: none;
padding: 20px 10px 0 10px;
margin: 0;
height: 347px;
overflow: scroll;
}
.messages .message {
clear: both;
overflow: hidden;
margin-bottom: 20px;
transition: all 0.5s linear;
opacity: 0;
}
.messages .message.right .text {
color: #45829b;
}
.messages .message.appeared {
opacity: 1;
}
.messages .message .avatar {
width: 60px;
height: 60px;
border-radius: 50%;
display: inline-block;
}
.messages .message .text_wrapper {
display: inline-block;
padding: 20px;
border-radius: 6px;
width: calc(100% - 85px);
min-width: 100px;
position: relative;
}
.messages .message .text_wrapper::after, .messages .message .text_wrapper:before {
top: 18px;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.messages .message .text_wrapper::after {
border-width: 13px;
margin-top: 0px;
}
.messages .message .text_wrapper::before {
border-width: 15px;
margin-top: -2px;
}
.messages .message .text_wrapper .text {
font-size: 18px;
font-weight: 300;
}
.bottom_wrapper {
position: relative;
width: 100%;
background-color: #fff;
padding: 20px 20px;
position: absolute;
bottom: 0;
}
.bottom_wrapper .message_input_wrapper {
display: inline-block;
height: 50px;
border-radius: 5px;
border: 1px solid #bcbdc0;
width: calc(100% - 160px);
position: relative;
padding: 0 20px;
word-wrap: break-word;
word-break: break-word;
-webkit-hyphens: auto;
-ms-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}
.bottom_wrapper .message_input_wrapper .message_input {
border: none;
height: 100%;
box-sizing: border-box;
width: calc(100% - 40px);
position: absolute;
outline-width: 0;
outline:none;
color: gray;
}
.bottom_wrapper .send_message {
width: 140px;
height: 50px;
display: inline-block;
border-radius: 7px;
background-color: #a3d063;
border: 2px solid #a3d063;
color: #fff;
cursor: pointer;
transition: all 0.2s linear;
text-align: center;
float: right;
}
.bottom_wrapper .send_message:hover {
color: #a3d063;
background-color: #fff;
}
.bottom_wrapper .send_message .text {
font-size: 18px;
font-weight: 300;
display: inline-block;
line-height: 48px;
}
.message_template {
display: none;
}
</style>
<style type="text/css">
.answerbot-input
{
color: #1AA1E1;
}
.answerbot-ai
{
color: #CE5043;
}
</style>
</head><body>
<div class="chat_window"><div class="top_menu"><div class="buttons"><div class="button close"></div><div class="button minimize"></div><div class="button maximize"></div></div><div class="title">Chat</div></div>
<div class="bottom_wrapper clearfix">
<div class="subcontent" id='subcontent'>
<p class='answerbot-ai'>
Don't be afraid, talk to me.
</p>
</div>
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." onkeyup="keypressInput(this, event);"/>
</div><div class="send_message">
<div class="icon"></div><div class="text">Send</div></div></div></div>
</li></div>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript">
var _answerBot = new answerBot();
function keypressInput(sender, event) {
if (event.which == 13) {
document.getElementById('subcontent').innerHTML += _answerBot.processInput(sender.value);
sender.value = '';
}
}
</script>
</body></html>
This is the scripts.js file:
var answerBot = function () {
var _this = this;
_this.processInput = function (text) {
updateUrl(text);
var _result = "<p class='answerbot-input'>" + text + "</p>";
text = text.replace(new RegExp("[ ]{2,}", "g"), " ");
var _words = text.toLowerCase().split(" ");
var _answers = [];
var _title = "";
if (_words.length === 0 || _words.toString() === '') { //if the input is empty
_answers = _this.specialContext.emptyInput;
_title = _this.specialContext.emptyInput;
} else {
var _possibleAnswers = findMatches(_words);
if (_possibleAnswers.length === 0) { //if no answer found
_answers = _this.specialContext.wrongInput;
_title = _this.specialContext.wrongInput;
}
if (_possibleAnswers.length == 1) { //context recognized
_answers = _this.answers[_possibleAnswers[0]].values;
_title = _this.answers[_possibleAnswers[0]].description;
}
if (_possibleAnswers.length > 1) {
_result += formatText(_this.specialContext.rephrase, _this.specialContext.rephrase);
for (var i = 0; i < _possibleAnswers.length; i++) {
_result += formatText(_this.answers[_possibleAnswers[i]].description, _this.answers[_possibleAnswers[i]].description);
}
}
}
if (_answers.length > 0) {
var _rand = Math.floor((Math.random() - 0.001) * _answers.length);
_result += formatText(_answers[_rand], _title);
}
return _result;
};
function formatText(text, title) {
return "<p class=\'answerbot-ai\' title=\'" + title + "\'>" + text + "</p>";
}
function findMatches(words) {
var foundKeywords = [];
var _possibleAnswers = [];
for (var i = 0; i < _this.keywords.length; i++) {
foundKeywords[i] = 0;
for (var j = 0; j < words.length; j++) {
if (_this.keywords[i].keys.indexOf(words[j]) >= 0) {
foundKeywords[i]++;
if (foundKeywords[i] == _this.keywords[i].keys.length) {
return [_this.keywords[i].value];
}
}
}
if (foundKeywords[i] * 2 > _this.keywords[i].keys.length) {
_possibleAnswers.push(_this.keywords[i].value);
}
}
return _possibleAnswers.filter(function (elem, pos) {
return _possibleAnswers.indexOf(elem) == pos;
});
}
function updateUrl(text){
history.pushState(null, null, "#question=" + encodeURIComponent(text));
if(typeof ga === "function")//google analytics
ga('send', 'event', 'question', text);
}
};
And this is the data.js file:
if (answerBot) {
answerBot.prototype.specialContext = {
"wrongInput": ["I don't understand you.", "Could you rephrase the question?"],
"emptyInput": ["Please say something", "Speak louder", "Well i can't read minds."],
"rephrase": ["Can you tell me if your question was about one of the following things:"]
};
answerBot.prototype.keywords = [
{ "keys": ["hi"], "value": 0 },
{ "keys": ["hello"], "value": 0 },
{ "keys": ["life", "universe", "everything"], "value": 1 },
{ "keys": ["software", "development"], "value": 2 },
{ "keys": ["software", "engineering"], "value": 2 },
{ "keys": ["who", "made", "you"], "value": 3 },
{ "keys": ["who", "wrote", "you"], "value": 3 },
{ "keys": ["who", "coded", "you"], "value": 3 },
{ "keys": ["is", "this", "real", "life"], "value": 4 },
{ "keys": ["who", "is", "deni"], "value": 5 },
{ "keys": ["tell", "me", "about", "deni"], "value": 5 },
{ "keys": ["tell", "me", "about", "author"], "value": 5 },
{ "keys": ["show", "me", "author"], "value": 5 },
{ "keys": ["can", "see", "source"], "value": 6 },
{ "keys": ["can", "see", "sourcecode"], "value": 6 },
{ "keys": ["show", "me", "code"], "value": 6 },
{ "keys": ["how", "are", "you"], "value": 7 },
{ "keys": ["who", "is", "this"], "value": 8 }];
answerBot.prototype.answers = [
{
"description": "Hi!",
"values": ["Hello there!", "Hi how can I help you today", "Hi! What brings you here?"]
},
{
"description": "What is the answer to life the universe and everything?",
"values": ["42"]
},
{
"description": "What is software development?",
"values": ["Programming! Do you speak it?"]
},
{
"description": "Who created me?",
"values": ["I was created by another <a href='http://about.me/deni' target='_blank'>bot</a>.", "The question is who sent you here?"]
},
{
"description": "Is this real life?",
"values": ["No this is the internetz!", "Find out <a href='http://www.youtube.com/watch?v=txqiwrbYGrs' target='_blank'>yourself</a>!"]
},
{
"description": "Who is Deni?",
"values": ["This is his <a href='https://plus.google.com/+DeniSpasovski/' target='_blank'>G+ profile</a>.", "This is his <a href='www.linkedin.com/in/denispasovski' target='_blank'>Linkedin profile</a>."]
},
{
"description": "Where is your source?",
"values": ["Here is the <a href='https://github.com/denimf/Answer-bot' target='_blank'>source</a>."]
},
{
"description": "How are you?",
"values": ["I'm good how are you?"]
},
{
"description": "Who is this?",
"values": ["StackOverflow Exception occurred", "The question is who are you?"]
}
];
}
As you can see, the chat works very well answering questions and I'm looking forward to implementing it with the questions I want to be answered. However, I'm having some issues that, despite how much I try, I can't seem to fix! (I don't know that much about coding, I apologize in advance!)
I can't fix the title on top. If you write enough, it will end up disappearing because new messages push it out of the chat window.
I can't seem to allow scrolling to see past messages... I've tried with overflow scroll and it doesn't work... The messages are fixed and I can't move up the timeline
I can't get the Send button to work either! The chat only works with the Enter key.
Thank you very much!!

Categories