При проверке совпадения имени страны, с правильным ответом, даже при неправильности ответа выводит совпадение
Решил сделать гео викторину, используя API rest-countries, придумал алгоритм, при котором я рандомно из 250 ответов апи, выбираю 4 из них и передаю в тег имена стран этих ответов, дальше методом slice я в этом массиве, состоящем из 4 рандомно выбранных стран, заменяю 1 рандомно выбранную страну, на правильную страну, совпадающую с флагом, первая прогузка API работает отлично, проверки на кнопках с ответами правильно определяют ответ, дальше что-то в алгоритме сбивается и проверки работают некорректно, выдавая неправильные ответы за правильные и так далее, что интересно, счётчик счёта, который при правильном ответе увеличивается на +100, при нажатии на некоторые неправильные ответы увеличивается сразу на +200, так же и с выводом в консоль, "correct" выводится дважды, при нажатии на некоторые кнопки. Пробовал менять проверки, не получается, если есть у кого-то какие-то идеи, буду рад услышать, за ранее извиняюсь за ужасный код, учу джаваскрипт всего 3 месяца.
Код html
<!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">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class = "wrapper">
<div id = "container" class="container hidden">
<div class="title-container">
<div class="title-name">
<h1>Geo<span><i class="fa-solid fa-earth-americas"></i></span> Quiz</h1>
</div>
<div class="title-score">
<p>Score : </p>
<!-- <h1 id = "score" value = 100></h1> -->
<input type="text" id = "score" value = 0 readonly>
</div>
</div>
<div class = "question-container">
<p class = "question">Which countries <span>flag</span> is this?</p>
</div>
<div class = "flag-container">
<img class = "flag-img"id = "img" src="https://3.bp.blogspot.com/-sCTPmY04Ft0/W0ENi2S6d5I/AAAAAAAApBg/T-c6c4j8AvAB3iKm5oMfdsk6LYnoI5TuQCLcBGAs/w1200-h630-p-k-no-nu/all_country_flags_with_names.jpg" alt="">
</div>
<div class="hint-container">
<a id = "btn-hint" class = "hint-btn" href="#">Get a hint<span></span></a>
<p id = "hint" class = "hint hide-hint">This country somewhere in <spani id = "hintAnswer">Asia</spani></p>
</div>
<div class="answers-container">
<div id = "answers" class = "answers">
<a href = "#" id = "var1" class = "answer ">
<span>A</span>Variant 1
<span id = "correctIncorrect" class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
</span>
</a>
<a href = "#" id = "var2" class = "answer ">
<span>B</span>Variant 2
<span id = "correctIncorrect" class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
</span>
</a>
<a href = "#" id = "var3" class = "answer">
<span>C</span>Variant 3
<span id = "correctIncorrect" class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
</span>
</a>
<a href = "#" id = "var4"class = "answer">
<span>D</span>Variant 4
<span id = "correctIncorrect" class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
</span>
</a>
</div>
</div>
<div class="next-btn-container">
<a href="#" id = "next-btn"class = "next-btn">Next Question</a>
</div>
</div>
</div>
<div class="btn-container">
<button class = "btn-start " id = "btn-start">Start QUIZ</button>
</div>
<!-- <input readonly type="text" id = "score" value = 0> -->
<script src="https://kit.fontawesome.com/0b0db4d2c6.js" crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>
Javascript
// Elements
const nextBtn = document.getElementById("next-btn")
const btnStart = document.getElementById("btn-start")
const btnHint = document.getElementById("btn-hint")
const hint = document.getElementById("hint")
const hintAnswer = document.getElementById("hintAnswer")
const container = document.getElementById("container")
const score = document.getElementById("score")
const answersContainer = document.getElementById("answers")
const correctIncorrect = document.getElementById("correctIncorrect")
const var1 = document.getElementById("var1")
const var2 = document.getElementById("var2")
const var3 = document.getElementById("var3")
const var4 = document.getElementById("var4")
const main = document.getElementById("main")
const img = document.getElementById("img")
const nativeName = document.getElementById("nativeName")
var isHidden = true
// Api components
const API_URL = "https://restcountries.com/v3.1/all"
async function getCountries(url) {
try {
const res = await fetch(url)
const data = await res.json()
const randomNumberFormCountries = Math.floor(Math.random() * 250)
const country = data[randomNumberFormCountries]
const { flags, continents, name } = country
const randomCountryName1 = data[Math.floor(Math.random() * data.length)].name.common
const randomCountryName2 = data[Math.floor(Math.random() * data.length)].name.common
const randomCountryName3 = data[Math.floor(Math.random() * data.length)].name.common
const randomCountryName4 = data[Math.floor(Math.random() * data.length)].name.common
console.log(name.common)
const correctAnswer = name.common
const incorrectAnswers = [randomCountryName1,randomCountryName2,randomCountryName3,randomCountryName4]
// <----------- Placing data on screen
hintAnswer.textContent = continents
img.src = flags.png
// <----------- Replacing 1 incorrectanswer with correct one
incorrectAnswers.splice(Math.floor(Math.random() * 4), 1, correctAnswer)
console.log(incorrectAnswers)
var1.innerHTML = `<span>A</span>${incorrectAnswers[0]}
<span class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
<i class="fa-regular fa-circle-xmark"></i>
</span>`
var2.innerHTML = `<span>B</span>${incorrectAnswers[1]}
<span class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
</span>`
var3.innerHTML = `<span>C</span>${incorrectAnswers[2]}
<span class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
</span>`
var4.innerHTML = `<span>D</span>${incorrectAnswers[3]}
<span class = "correct-incorrect hidden">
<i class="fa-regular fa-circle-check"></i>
</span>`
var1.addEventListener("click", (event) => {
if (incorrectAnswers[0] === correctAnswer) {
console.log("correct!")
score.value = parseInt(score.value) + 100
var1.classList.add("correct")
}else if(incorrectAnswers[0] !== correctAnswer) {
var1.classList.add("incorrect")
}
event.preventDefault()
})
var2.addEventListener("click", (event) => {
if (incorrectAnswers[1] === correctAnswer) {
console.log("correct!")
score.value = parseInt(score.value) + 100
var2.classList.add("correct")
}else {
var2.classList.add("incorrect")
}
event.preventDefault()
})
var3.addEventListener("click", (event) => {
if (incorrectAnswers[2] === correctAnswer) {
console.log("correct!")
score.textContent = parseInt(score.value) + 100
var3.classList.add("correct")
}else {
var3.classList.add("incorrect")
}
event.preventDefault()
})
var4.addEventListener("click", (event) => {
if (incorrectAnswers[3] === correctAnswer) {
console.log("correct!")
score.value = parseInt(score.value) + 100
var4.classList.add("correct")
}else {
var4.classList.add("incorrect")
}
event.preventDefault()
})
} catch (error) {
console.log(error)
}
}
function resetClasses() {
var1.classList.remove("correct")
var2.classList.remove("correct")
var3.classList.remove("correct")
var4.classList.remove("correct")
var1.classList.remove("incorrect")
var2.classList.remove("incorrect")
var3.classList.remove("incorrect")
var4.classList.remove("incorrect")
}
// Event listeners
nextBtn.addEventListener("click", (event)=>{
getCountries(API_URL)
event.preventDefault()
resetClasses()
})
btnStart.addEventListener("click", () => {
btnStart.classList.add("hidden")
container.classList.remove("hidden")
getCountries(API_URL)
})
btnHint.addEventListener("click", ()=>{
hint.classList.toggle("hide-hint")
})
CSS
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: "Poppins",sans-serif;
}
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
margin: 0 auto;
height: 100vh;
overflow: hidden;
background: #3498DB;
}
.wrapper{
background: #fff;
width: 35em;
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
border-radius: 3px;
}
.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
position: relative;
}
/* Title COntainer */
.title-container {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
border-bottom: 0.1px solid #ccc;
margin-bottom: 50px;
box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 2px, rgba(0, 0, 0, 0.23) 0px 1px 10px;
}
.title-container .title-name {
padding: 20px;
text-transform: uppercase;
}
.title-container .title-name span {
color:#000;
margin-left: 13px;
margin-right: 5px;
text-align: center;
}
.title-container .title-score {
display: flex;
justify-content: center;
align-items: center;
margin: 10px;
}
.title-container .title-score h1{
margin-left: 10px;
margin-right: 20px;
color: #76D7C4;
text-decoration: underline;
}
.title-container .title-score input {
color: rgb(74, 72, 72);
border: none;
/* border-bottom: 2px solid #ccc; */
margin-top: 3px;
margin-right: 40px;
padding-left: 5px;
font-size: 1.5em;
width: 100px;
font-weight: 600;
text-decoration: underline;
color:#52b9a4;
text-align: left;
}
/* <----------------> */
/* Question container */
.question-container{
margin-bottom: 5px;
font-size: 1.3em;
font-weight: 600;
color: rgb(61, 61, 61)
}
.question {
letter-spacing: 1px;
text-transform: uppercase;
}
.question span {
color: #EC7063;
}
/* <----------------> */
/* flag-container */
.flag-container {
margin: 20px 0 50px 0;
}
.flag-img {
box-shadow: rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px;
max-width: 350px;
max-height: 200px;
width: 350px;
height: 200px;
}
/* <----------------> */
/* Hint container */
.hint-container {
margin-bottom: 1em;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
}
.hint-btn {
text-decoration: none;
text-transform: uppercase;
margin-left: 5%;
font-size: 1.2em;
color: rgb(57, 57, 57);
background: #52b9a4;
padding: 5px 10px;
border-radius: 5px;
color: rgba(255, 255, 255, 0.753);
cursor: pointer;
transition: 0.3s ease;
}
.hint {
margin-right: 5%;
color: rgb(68, 68, 68);
font-size: 1em;
transition: 0.3s ease;
}
.hint span {
color:#EC7063;
font-weight: 600;
text-decoration: underline;
}
.hint-btn:hover{
color: #fff;
background: rgb(115, 197, 181);
}
.hint-btn:active {
transform: scale(0.95);
}
/* Answers container */
.answers-container {
border-top: 1px solid #ccc;
width: 100%;
margin-bottom: 50px;
padding-top: 20px;
}
.answers-container .answers {
}
.answers-container .answers .answer {
background-color: #D6EAF8;
display: block;
color: #000;
margin: 0px 20px;
padding: 20px 0;
text-decoration: none;
border: 2px solid #AED6F1;
border-radius: 5px;
font-size: 1.2em;
transition: 0.3s ease;
position: relative;
}
.answers-container .answers .answer:not(:last-child) {
margin-bottom: 6px;
}
.answers-container .answers .answer:hover{
transform: scale(1.02);
}
.answers-container .answers .answer span {
font-weight: 600;
padding-left: 0.6em;
padding-right: 1em;
}
/* <----------------> */
.correct-incorrect {
width: 100%;
position: absolute;
}
.next-btn-container {
margin-bottom: 7%
}
.next-btn {
text-decoration: none;
color: rgb(57, 57, 57);
font-size: 1.3em;
background: #3498DB;
padding: 10px 25px;
color: #fff;
border-radius: 5px;
letter-spacing: 1px;
transition: 0.3s ease;
}
.next-btn:hover {
background:#41a6ea ;
}
.btn-container {
}
.btn-start {
/* margin-right: 30%; */
padding: 30px 60px;
font-size: 2em;
font-family: 'Press Start 2P', cursive;
background-color: #3498DB;
color: #fff;
border: none;
border-radius: 15px;
cursor: pointer;
transition: 0.3s ease;
}
.btn-start:hover {
transform: scale(1.1);
background: #5DADE2;
}
.hidden {
display: none;
}
.correct {
background-color: #ABEBC6 !important;
}
.incorrect {
background-color: #fdc5bf!important;
}
.hide-hint {
opacity: 0;
}
@media(max-width: 450px) {
.btn-container {
position: absolute;
}
.title-container {
justify-content: center;
}
.title-container h1 {
font-size: 1.2em;
}
.hint-container {
text-align: center;
margin-bottom: 1em;
display: block
}
.hint {
margin-top: 10px;
}
.answers-container {
width: auto;
}
body {
background: #fff;
}
.wrapper {
box-shadow: none;
}
}
Это мой первый пост на данном форуме, за ранее прошу прощения за все возможные ошибки в создании поста!