how can i create random function - javascript

I am creating exam webpage, where from 3 arrays my code can randomly choose from each array 5 exercises. The 3 arrays are 1: easy level, 2: medium level and 3: hard level of exercises. There will be 50 exercises on each array with 3-4 answers. I already have some code, but i only use one array. Can you suggest some ways creating my webpage? Thanks in advance :)
Ps. language of webpage is armenian, sorry if you don't understand)
const paragraph = document.querySelector('#paragraph');
const params = new URLSearchParams(window.location.search);
params.forEach((value)=>{
paragraph.append(`${value}`);
paragraph.append(document.createElement("br"));
});
(function(){
// Functions
function buildQuiz(){
// variable to store the HTML output
const output = [];
// for each question...
myQuestions.forEach(
(currentQuestion, questionNumber) => {
// variable to store the list of possible answers
const answers = [];
// and for each available answer...
for(letter in currentQuestion.answers){
// ...add an HTML radio button
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`
);
}
// add this question and its answers to the output
output.push(
`<div class="slide">
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>
</div>`
);
}
);
// finally combine our output list into one string of HTML and put it on the page
quizContainer.innerHTML = output.join('');
}
function showResults(){
// gather answer containers from our quiz
const answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
let numCorrect = 0;
// for each question...
myQuestions.forEach( (currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
// if answer is correct
if(userAnswer === currentQuestion.correctAnswer){
// add to the number of correct answers
numCorrect++;
// color the answers green
answerContainers[questionNumber].style.color = 'lightgreen';
}
// if answer is wrong or blank
else{
// color the answers red
answerContainers[questionNumber].style.color = 'red';
}
});
// show number of correct answers out of total
resultsContainer.innerHTML = `you got ${numCorrect} out of ${myQuestions.length}`;
}
function showSlide(n) {
slides[currentSlide].classList.remove('active-slide');
slides[n].classList.add('active-slide');
currentSlide = n;
if(currentSlide === 0){
previousButton.style.display = 'none';
}
else{
previousButton.style.display = 'inline-block';
}
if(currentSlide === slides.length-1){
nextButton.style.display = 'none';
submitButton.style.display = 'inline-block';
}
else{
nextButton.style.display = 'inline-block';
submitButton.style.display = 'none';
}
}
function showNextSlide() {
showSlide(currentSlide + 1);
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
// Variables
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');
const myQuestions = [
{
question: "Լուծել հավասարումը 3 - x > 1",
answers: {
a: "(-∞ ; 2]",
b: "(2 ; +∞)",
c: "(-∞ ; 2)",
d: "[2 ; +∞)"
},
correctAnswer: "c"
},
{
question: "Շրջանագծի հավասարումն է (x + 2)2 + (y + 1)2 = 13, գտնել շոշափողի թեքությունը",
answers: {
a: "-2/3",
b: "Չգիտեմ",
c: "5",
d: "2/3"
},
correctAnswer: "a"
},
{
question: "x<sup>2</sup> - 3|x - 2| - 4x = - 6 հավասարումից գտնել x-ը",
answers: {
a: "Չգիտեմ",
b: "4, 0, 3, 1",
c: "8, 9, 15",
d: "5"
},
correctAnswer: "b"
},
{
question: "hello",
answers: {
a: "Չգիտեմ",
b: "hi",
c: "duck",
d: "lol"
},
correctAnswer: "b"
}
];
buildQuiz();
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
showSlide(currentSlide);
submitButton.addEventListener('click', showResults);
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
})();
#import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);
body{
font-size: 20px;
font-family: 'Work Sans', sans-serif;
color: #333;
font-weight: 300;
text-align: center;
background-color: #f8f6f0;
}
h1{
font-weight: 300;
margin: 0px;
padding: 10px;
font-size: 20px;
background-color: #444;
color: #fff;
border-radius: 3px;
}
.question{
font-size: 30px;
margin-bottom: 10px;
}
.answers {
margin-bottom: 20px;
text-align: left;
display: inline-block;
}
.answers label{
display: block;
margin-bottom: 10px;
}
button{
font-family: 'Work Sans', sans-serif;
font-size: 22px;
background-color: #279;
color: #fff;
border: 0px;
border-radius: 3px;
padding: 20px;
cursor: pointer;
margin-bottom: 20px;
}
.in{
font-family: 'Work Sans', sans-serif;
font-size: 22px;
background-color: #fff;
color: #444;
border: 0px;
border-radius: 3px;
padding: 20px;
cursor: pointer;
margin-bottom: 20px;
}
button:hover{
background-color: #38a;
}
.slide{
position: absolute;
left: 0px;
top: 0px;
width: 100%;
z-index: 1;
opacity: 0;
transition: opacity 0.5s;
}
.active-slide{
opacity: 1;
z-index: 2;
}
.quiz-container{
position: relative;
height: 200px;
margin-top: 40px;
}
.but{
font-family: 'Work Sans', sans-serif;
font-size: 22px;
background-color: #279;
color: #fff;
border: 0px;
border-radius: 3px;
padding: 20px;
cursor: pointer;
margin-bottom: 20px;
}
#paragraph{
text-align: left;
background-color: rgba(68, 68, 68, 0.315);
width: max-content;
border-radius: 3px;
}
<!DOCTYPE html>
<html lang="hy">
<head>
<link rel="stylesheet" href="style.css">
<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>11 քննություն</title>
<link rel="stylehseet" href="style.css">
</head>
<body>
<br><h1>Երևանի Գալուստ Գյուլբենկյանի անվան համար 190 ավագ դպրոց
<br><br>Մաթեմատիկայի առցանց քննություն
<br><br>11-րդ դասարանի մաթեմատիկա</h1><br>
<p id="paragraph"></p>
<div class="quiz-container">
<div id="quiz"></div>
</div><br><br><br>
<button id="previous">Նախորդ խնդիրը</button>
<button id="next">Հաջորդ խնդիրը</button>
<button id="submit">Ստուգել պատասխանները</button>
<div id="results"></div>
<script src="script11.js"></script>
</body>
</html>

I would suggest to create a js function with 2 parameters. The first parameter is the array with all exercises (easy / medium / hard). Second parameter would be the amount how many results do you want to get. So it would look something like this:
function getRandomExercises(exercises, exerciseAmount) {
const result = [];
for(let i = 0; i < exerciseAmount; i++) {
result.push(exercises[Math.floor(Math.random()*exercises.length)])
}
return result;
}
Then you could call the function with the different levels of you app like so:
getRandomExercises(easyExercises, 5);
getRandomExercises(mediumExercises, 5);
getRandomExercises(hardExercises, 5);

Related

how to play audio file on each question on javascript

var questions = [];
var images = {}
So, the inside of "questions" array have another array that can call "images" array the problem here is how to call the "audio array" i have made an array for the audio but it seems not working
var sounds ={}
I have also tried another method which is putting html element inside of the array of variables but still, it's not working
HTML css
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Picture Quiz</title>
<style>
body {
background-color: #eeeeee;
}
.grid {
width: 68%;
height: 520px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.buttons img
{
width:200px;
}
.grid h1 {
font-family: "sans-serif";
background-color: #ffc107;
font-size: 35px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
hr
{
margin-top: 50px;
color: red;
background-color: #ffc107;
height: 2px;
border: none;
}
#score {
color: #ffc107;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #ffc107;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
padding: 0px;
font-size: 20px;
color: #fff;
border: none;
margin: 10px 20px 10px 0px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #ffc107;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
</style>
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Picture Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<p id="audio"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>
Javascript
var images = {
"dog": "dog.jpg",
"cow": "cow.jpg",
"cat": "cat.jpg",
"goat": "goat.jpg",
"deer": "deer.jpg",
"hen": "hen.jpg",
"lion": "lion.jpg",
"parrot": "parrot.jpg",
"tiger": "tiger.jpg"
}
var sounds = {
"audio1" : "grizz.mp3",
"audio2" : "immortal.mp3",
"audio3" : "genshoshi.mp3",
"audio4" : "genshoshi.mp3",
"audio5" : "immortal.mp3"
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show audio
var audio = document.getElementById("audio");
audio.innerHTML = quiz.getQuestionIndex().audio;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question(["Which one is dog?"],"audio1",["cow", "goat", "cat", "dog"], "dog"),
new Question(["select tiger below"],"audio2",["parrot", "deer", "tiger", "lion"], "tiger"),
new Question(["choose parrot pls?"],"audio3",["hen", "parrot", "goat", "dog"], "parrot"),
new Question(["Find cat below?"],"audio4",["parrot", "goat", "cat", "tiger"], "cat"),
new Question(["choose lion pls?"],"audio5",["lion", "goat", "tiger", "dog"], "lion")
];
questions.sort(function(){
return 0.5 - Math.random();
});
function Question(text, audio , choices, answer) {
this.text = text;
this.audio = audio;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
I'm trying to make text sound1 into an audio button that can be played as my quiz later
For audio, you have to make an html element and grab that element by using its id and audio will only play when the user triggers it like when clicked it will not be automatically played.
You can refer this site for more information.
And please don't copy paste whole code while asking question, paste whatever is required.

How to reload all kinds of functions and all HTML code in JavaScript to restart a game?

Clicking on the Home button at the end of this project brings it to the beginning, but no function is reset. Level buttons are not also being enabled anew. If I enable those level buttons by writing some extra code for enabling, then the number of buttons given for each level will be doubled after selecting the level. In other words, for the first time due to selecting the basic level, there were 4 options, But when I click on the last home button and then select the medium level to play the game from the beginning, it becomes 16 options instead of 8.
//VARIABLE DECLARATION PART
let frontpage = document.querySelector(".front-page");
let playbutton = document.querySelector(".play");
let levelpage = document.querySelector(".levelpg");
let startbtn = document.querySelector(".startbtn");
let maingame = document.querySelector(".maingame");
let easybtn = document.querySelector(".easy");
let mediumbtn = document.querySelector(".medium");
let hardbtn = document.querySelector(".hard");
let nextbtn = document.querySelector(".nextbtn");
let pagecount = document.querySelector('.gamepagecount');
let getnumberdiv = document.querySelector('.numberbtn').children;
let resultpg = document.querySelector('.resultpage');
let backhome = document.querySelector('.backhome');
let finalscore = document.querySelector('.score');
let resulttext = resultpg.children[1];
let changeimg = document.querySelector('.resultpage img');
// PLAYBUTTON CLICK
playbutton.addEventListener("click", () => {
frontpage.classList.add("hidden");
levelpage.classList.remove("hidden");
levelpage.classList.add("visibility");
});
//GAME START FUNCTION
function startGame(level) {
if (level == "easy") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
easybtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 10`;
nextbtn.disabled = true
levelChange(4);
gameInterfaceChange()
mainGame(10);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(4)
pageCount(10);
mainGame(10);
})
});
}
else if (level == "medium") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
mediumbtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 15`;
nextbtn.disabled = true
levelChange(8);
gameInterfaceChange();
maingame.style.top = "20%";
mainGame(20);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(8)
pageCount(15)
mainGame(20);
})
});
}
else if (level == "hard") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
hardbtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 20`;
nextbtn.disabled = true
levelChange(12);
gameInterfaceChange();
maingame.style.top = "12%";
mainGame(30);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(12)
pageCount(20)
mainGame(30);
})
});
}
}
//PAGE SLIDING FUNCTION
function gameInterfaceChange() {
levelpage.classList.remove("hidden");
levelpage.classList.add("hidden");
maingame.classList.remove("hidden");
maingame.style.top = "25%";
maingame.classList.add("visibility");
}
// FUNCTION OF RANDOM INPUTING NUMBER IN DIV
function mainGame(maxnum) {
let numboxlen = getnumberdiv.length;
let wrongnum = Math.floor(Math.random() * maxnum) + 1;
let getnumber = [];
//DUPLICATE RANDOM NUMBER CHECKING
for (let i = 0; i < numboxlen; i++) {
let check = getnumber.includes(wrongnum);
if (check === false) {
getnumber.push(wrongnum);
}
else {
while (check === true) {
wrongnum = Math.floor(Math.random() * maxnum) + 1;
check = getnumber.includes(wrongnum);
if (check === false) {
getnumber.push(wrongnum);
}
}
}
}
// NUMBER PUTTING IN InnerHtml
for (var j = 0; j < numboxlen; j++) {
if (getnumber[j] < 10) {
getnumberdiv[j].innerHTML = '0' + getnumber[j];
}
else {
getnumberdiv[j].innerHTML = getnumber[j];
}
}
}
// BUTTON ADDING ACCORDING TO THE LEVEL
function levelChange(divnum) {
for (let index = 0; index < divnum; index++) {
let newBtn = document.createElement('button');
let newbtnNode = document.createTextNode('');
newBtn.appendChild(newbtnNode);
let gamebtn = document.getElementById('numbrbtn');
gamebtn.appendChild(newBtn);
newBtn.setAttribute("onclick", `numberClick(${index},${divnum})`);
}
}
//RIGHT - WRONG CHECKING FUNTION
var right = 0;
var wrong = 0;
function numberClick(index, divnum) {
let rightnumberindex = Math.floor(Math.random() * divnum);
if (index == rightnumberindex) {
nextbtn.disabled = false
right++;
//RIGHT AND WRONG BACKGROUND ADDING AND BUTTON DISABLE
getnumberdiv[index].classList.add("rightans");
for (let i = 0; i < divnum; i++) {
getnumberdiv[i].disabled = true;
}
}
else {
nextbtn.disabled = false
wrong++;
//RIGHT AND WRONG BACKGROUND ADDING AND BUTTON DISABLE
getnumberdiv[rightnumberindex].classList.add("rightans");
getnumberdiv[index].classList.add("wrongans");
for (let i = 0; i < divnum; i++) {
getnumberdiv[i].disabled = true;
}
}
}
// BUTTON ENABLE ON NEXT BUTTION CLICK
function enableBtn(divnum) {
for (let i = 0; i < divnum; i++) {
nextbtn.disabled = true
getnumberdiv[i].disabled = false;
getnumberdiv[i].classList.remove("wrongans");
getnumberdiv[i].classList.remove("rightans");
}
}
//PAGE COUNTING ACCORDING TO THE LEVEL
let currentpg = 1;
function pageCount(levelPg) {
currentpg++;
if (currentpg <= levelPg) {
if (currentpg == levelPg) {
nextbtn.innerHTML = 'Result'
pagecount.innerHTML = `${currentpg} of ${levelPg}`;
}
else {
pagecount.innerHTML = `${currentpg} of ${levelPg}`;
}
}
else {
result();
}
}
//FINAL RESULT FUNTION
function result() {
maingame.classList.remove("visibility");
maingame.classList.add("hidden");
resultpg.classList.remove('hidden')
resultpg.classList.add('visibility')
if (right > wrong) {
changeimg.setAttribute('src', 'trophy.png')
resulttext.innerHTML = `You Win`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
else if (right == wrong) {
changeimg.setAttribute('src', 'draw.png')
resulttext.innerHTML = `It's Draw`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
else if (right < wrong) {
changeimg.setAttribute('src', 'lose.png')
resulttext.innerHTML = `You Lose`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
}
//BACK TO THE HOME FUNCTION
backhome.addEventListener('click', () => {
frontpage.classList.add("visibility");
frontpage.classList.remove("hidden");
resultpg.classList.add('hidden')
resultpg.classList.remove('visibility')
// enable level button
mediumbtn.disabled = false;
hardbtn.disabled = false;
easybtn.disabled = false;
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
margin-top: 50px;
}
.guessing-game {
position: relative;
color: white;
text-align: center;
margin: auto;
width: 350px;
height: 600px;
border-radius: 25px;
padding: 50px 30px;
background: linear-gradient(to right, #bd3f32, #cb356b);
}
.guessing-game .front-page .front-img {
height: 160px;
text-align: center;
}
.guessing-game .front-page img {
max-height: 100%;
}
.guessing-game .front-page .front-text h1 {
margin-top: 50px;
font-size: 1.8em;
}
.guessing-game .front-page .front-text p {
margin-top: 10px;
font-size: 1em;
}
.guessing-game .front-page .front-text button,
.resultpage button ,
.levelpg .easy,
.levelpg .medium,
.levelpg .hard,
.maingame .nextbtn {
margin-top: 30px;
width: 100%;
color: white;
padding: 15px;
outline: 0;
border: 0;
border-radius: 50px;
font-size: 0.9em;
background-color: #d64d5d;
box-shadow: rgba(17, 17, 26, 0.1) 0px 1px 0px,
rgba(17, 17, 26, 0.144) 0px 8px 24px, rgba(17, 17, 26, 0.1) 0px 16px 48px;
}
.guessing-game .front-page .front-text button:hover,
.maingame .nextbtn:hover,
.resultpage button:hover {
transition: 0.5s;
background-color: #c22f40;
}
/* Level page */
.visiblepg {
position: absolute;
top: 12%;
width: 290px;
}
.levelpg h1 {
margin: 45px 0 40px 0;
font-weight: 600;
font-size: 2.4em;
border: 1px solid white;
}
.levelpg .easy,
.levelpg .medium,
.levelpg .hard {
display: block;
margin-top: 15px;
padding: 12px;
background: white;
font-size: 1em;
border-radius: 10px;
font-weight: 400;
color: #c22f40;
}
.startbtn {
background: transparent;
border: 0;
outline: 0;
}
.levelpg i {
color: white;
margin-top: 50px;
font-size: 70px;
border-radius: 50%;
border: 2px solid transparent;
}
.levelpg i:hover {
background-color: white;
border: 2px solid white;
color: #c22f40;
transition: 0.5s;
}
/* GAME PART */
.maingame .gamepagecount {
background-color: #d64d5d;
color: white;
padding: 4px;
border-radius: 6px;
font-size: 0.8em;
font-weight: 600;
}
.maingame .gametext {
margin-top: 15px;
font-size: 1.2em;
}
.maingame .numberbtn {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.maingame .numberbtn button {
margin-top: 40px;
width: 50px;
height: 50px;
background-color: white;
display: flex;
align-content: space-around;
justify-content: center;
align-items: center;
flex-wrap: wrap;
flex: 1 0 21%;
margin-left: 10px;
border: 0;
outline: 0;
border-radius: 10px;
font-size: 1em;
color: #c22f40;
font-weight: 600;
}
.maingame .numberbtn button:nth-child(1),
.maingame .numberbtn button:nth-child(5),
.maingame .numberbtn button:nth-child(9) {
margin-left: 0;
}
.resultpage h1 {
margin: 0px 0 40px 0;
}
.resultpage img {
margin-top: 45px;
width: 50%;
}
/* PRE DEFINE CSS */
.visibility {
visibility: visiible;
opacity: 2s;
transition: 0.5s;
transform: translateX(0px);
}
.hidden {
visibility: hidden;
opacity: 0;
transition: 0.5s;
transform: translateX(-30px);
}
.levelcolor {
transition: 0.5s;
color: white !important;
background-color: #c22f40 !important;
}
.rightans {
background-color: #27ae60 !important;
color: white !important;
transition: 0.5s;
}
.wrongans {
background-color: #fd4631 !important;
color: white !important;
transition: 0.5s;
}
<!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="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
rel="stylesheet" />
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"
integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<title>Guessing Game</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="guessing-game">
<div class="front-page">
<div class="front-img">
<img src="./question.png" alt="" />
</div>
<div class="front-text">
<h1>Guessing Game</h1>
<p>
You just need to chose the right number from the option. If your
guess is right more than wrong , you will win otherwise you will
fail! Let's see how good your sixth sense is!!!
</p>
<button class="play">Let's play</button>
</div>
</div>
<div class="levelpg hidden visiblepg">
<h1>Game level</h1>
<button class="easy" onclick="startGame('easy')">Easy</button>
<button class="medium" onclick="startGame('medium')">Medium</button>
<button class="hard" onclick="startGame('hard')">Hard</button>
<button class="startbtn"><i class="fas fa-play-circle"></i></button>
</div>
<div class="maingame visiblepg hidden">
<p class="gamepagecount">1</p>
<p class="gametext">Guess the number you think is right</p>
<div class="numberbtn" id="numbrbtn"></div>
<button class="nextbtn">Next</button>
</div>
<div class="resultpage levelpg hidden visiblepg">
<img src="" alt="" />
<h1></h1>
<div class="score"></div>
<button class="backhome">Home</button>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
In short, as soon as I click on the home button, I want the game to start anew, all the functions will be reset anew, and the HTML will be reset anew also. I hope my problem is enough clear to understand.
I have solved the problem.
I just add a reload function to solve this problem.
backhome.addEventListener('click', () => {
frontpage.classList.add("visibility");
frontpage.classList.remove("hidden");
resultpg.classList.add('hidden')
resultpg.classList.remove('visibility')
//reload function
window.location.reload();
})

Function removes items from localStorage only if run manually

I'm looking for advice/tips on how to fix a function that is supposed to remove items from localStorage. I'm following a tutorial by John Smilga that I found on Youtube. Although I've modeled my code on his, apparently, I have missed something.
This function works perfectly well if I run it manually from the console and pass in the id of the item that I want to remove from localStorage.
function removeFromLocalStorage(id) {
console.log(id);
let storageItems = getLocalStorage();
console.log(storageItems);
storageItems = storageItems.filter(function(singleItem) {
if (singleItem.id !== id) {
return singleItem;
}
})
console.log(storageItems);
localStorage.setItem("list", JSON.stringify(storageItems));
}
However, when this function is triggered by the deleteItem() function, it refuses to remove the item from localStorage. It still works, there are a bunch of console.logs in it that track its execution, and I can check that it receives the correct item id as the argument, but for some reason it doesn't filter out the item that needs to be removed. I am completely lost and have no idea how to identify the problem. I can't debug it with console.logs as I usually do. I will be very grateful if you help me find the problem. Any advice will be appreciated.
In case the entire code is needed, please find it below.
const form = document.querySelector(".app__form");
const alert = document.querySelector(".app__alert");
const input = document.querySelector(".app__input");
const submitBtn = document.querySelector(".app__submit-btn");
const itemsContainer = document.querySelector(".app__items-container");
const itemsList = document.querySelector(".app__items-list");
const clearBtn = document.querySelector(".app__clear-btn");
let editElement;
let editFlag = false;
let editId = "";
form.addEventListener("submit", addItem);
clearBtn.addEventListener("click", clearItems);
function addItem(e) {
e.preventDefault();
const id = Math.floor(Math.random() * 9999999999);
if (input.value && !editFlag) {
const item = document.createElement("div");
item.classList.add("app__item");
const attr = document.createAttribute("data-id");
attr.value = id;
item.setAttributeNode(attr);
item.innerHTML = `<p class='app__item-text'>${input.value}</p>
<div class='app__item-btn-cont'>
<button class='app__item-btn app__item-btn--edit'>edit</button>
<button class='app__item-btn app__item-btn--delete'>delete</button>
</div>`
const editBtn = item.querySelector(".app__item-btn--edit");
const deleteBtn = item.querySelector(".app__item-btn--delete");
editBtn.addEventListener("click", editItem);
deleteBtn.addEventListener("click", deleteItem);
itemsList.appendChild(item);
displayAlert("item added", "success");
addToLocalStorage(id, input.value);
setBackToDefault();
itemsContainer.classList.add("app__items-container--visible");
} else if (input.value && editFlag) {
editElement.textContent = input.value;
// edit local storage
editLocalStorage(editId, input.value);
setBackToDefault();
displayAlert("item edited", "success");
} else {
displayAlert("empty field", "warning");
}
}
function setBackToDefault() {
input.value = "";
editFlag = false;
editId = "";
submitBtn.textContent = "Submit";
submitBtn.className = "app__submit-btn";
}
function displayAlert(text, action) {
alert.textContent = text;
alert.classList.add(`app__alert--${action}`);
setTimeout(function() {
alert.textContent = "";
alert.classList.remove(`app__alert--${action}`);
}, 700)
}
function clearItems() {
const items = document.querySelectorAll(".app__item");
if (items.length > 0) {
items.forEach(function(singleItem) {
itemsList.removeChild(singleItem);
})
itemsContainer.classList.remove("app__items-container--visible");
displayAlert("items cleared", "cleared");
setBackToDefault();
}
}
function editItem(e) {
const item = e.currentTarget.parentElement.parentElement;
editElement = e.currentTarget.parentElement.previousElementSibling;
editId = item.dataset.id;
editFlag = true;
input.value = editElement.textContent;
submitBtn.textContent = "Edit";
submitBtn.classList.add("app__submit-btn--edit");
input.focus();
}
function deleteItem(e) {
const item = e.currentTarget.parentElement.parentElement;
const itemId = item.dataset.id;
removeFromLocalStorage(itemId);
displayAlert("item removed", "cleared");
setBackToDefault();
itemsList.removeChild(item);
if (itemsList.children.length === 0) {
itemsContainer.classList.remove("app__items-container--visible");
}
}
function addToLocalStorage(id, value) {
const itemsObj = {id: id, value: input.value};
let storageItems = getLocalStorage();
storageItems.push(itemsObj);
localStorage.setItem("list", JSON.stringify(storageItems));
}
function removeFromLocalStorage(id) {
console.log(id);
let storageItems = getLocalStorage();
console.log(storageItems);
storageItems = storageItems.filter(function(singleItem) {
if (singleItem.id !== id) {
return singleItem;
}
})
console.log(storageItems);
localStorage.setItem("list", JSON.stringify(storageItems));
}
function editLocalStorage(id, value) {
}
function getLocalStorage() {
return localStorage.getItem("list") ? JSON.parse(localStorage.getItem("list")) : [];
}
* {
margin: 0;
padding: 0;
}
.app {
width: 70%;
max-width: 600px;
margin: 75px auto 0;
}
.app__title {
text-align: center;
/* color: #1B5D81; */
margin-top: 20px;
color: #377FB4;
}
.app__alert {
width: 60%;
margin: 0 auto;
text-align: center;
font-size: 20px;
color: #215884;
border-radius: 7px;
height: 23px;
transition: 0.4s;
text-transform: capitalize;
}
.app__alert--warning {
background-color: rgba(243, 117, 66, 0.2);
color: #006699;
}
.app__alert--success {
background-color: rgba(165, 237, 92, 0.4);
color: #3333ff;
}
.app__alert--cleared {
background-color: #a978da;
color: white;
}
.app__input-btn-cont {
display: flex;
margin-top: 30px;
}
.app__input {
width: 80%;
box-sizing: border-box;
font-size: 20px;
padding: 3px 0 3px 10px;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
border-right: none;
border: 1px solid #67B5E2;
background-color: #EDF9FF;
}
.app__input:focus {
outline: transparent;
}
.app__submit-btn {
display: block;
width: 20%;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
border-left: none;
background-color: #67B5E2;
border: 1px solid #67B5E2;
cursor: pointer;
font-size: 20px;
color: white;
transition: background-color 0.7s;
padding: 3px 0;
}
.app__submit-btn--edit {
background-color: #95CB5D;
}
.app__submit-btn:active {
width: 19.9%;
padding: 0 0;
}
.app__submit-btn:hover {
background-color: #377FB4;
}
.app__submit-btn--edit:hover {
background-color: #81AF51;
}
.app__items-container {
visibility: hidden;
/* transition: 0.7s; */
}
.app__items-container--visible {
visibility: visible;
}
.app__item {
display: flex;
justify-content: space-between;
margin: 20px 0;
}
.app__item:hover {
background-color: #b9e2fa;
border-radius: 10px;
}
.app__item-text {
padding-left: 10px;
font-size: 20px;
color: #1B5D81;
}
.app__item-btn-cont {
display: flex;
}
.app__item-btn-img {
width: 20px;
height: 20px;
}
.app__item-btn {
border: none;
background-color: transparent;
cursor: pointer;
display: block;
font-size: 18px;
}
.app__item-btn--edit {
margin-right: 45px;
color: #2c800f;
}
.app__item-btn--delete {
margin-right: 15px;
color: rgb(243, 117, 66);
}
.app__clear-btn {
display: block;
width: 150px;
margin: 20px auto;
border: none;
background-color: transparent;
font-size: 20px;
color: rgb(243, 117, 66);
letter-spacing: 2px;
cursor: pointer;
transition: border 0.3s;
border: 1px solid transparent;
}
.app__clear-btn:hover {
border: 1px solid rgb(243, 117, 66);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" name="viewport" content="width=device-width,
initial-scale=1">
<link rel="stylesheet" href="list.css">
<title>To Do List App</title>
</head>
<body>
<section class="app">
<form class="app__form">
<p class="app__alert"></p>
<h2 class="app__title">To Do List</h2>
<div class="app__input-btn-cont">
<input class="app__input" type="text" id="todo" placeholder="do stuff">
<button class="app__submit-btn">Submit</button>
</div>
</form>
<div class="app__items-container">
<div class="app__items-list">
</div>
<button class="app__clear-btn">Clear Items</button>
</div>
</section>
<script src="list.js"></script>
</body>
</html>
Your code is fine you just used the wrong comparison operator.
In your case you are comparing 2 IDs (operands) to see if they match up, so you should use normal operators such as (==, !=), but instead in your case, you have used strict operators which are used to compare the operand type and the operand itself.
You can learn more about Comparison Operators here.
Ultimatly,
In your function removeFromLocalStorage(id), you have an extra equal sign in your if function.
Instead of:
if (singleItem.id !== id) {
return singleItem;}
It should be:
if (singleItem.id != id) {
return singleItem;}
Hope this helps.

Loops with unexpected result

This is a color guessing game I'm working on. Basically it allows users to select a color out of six, and output correct if the color is the same as mentioned in the title or output try again if the color is wrong. When I try the first game, everything seems fine but when I select play again and select the colors again, an unexpected recursion occurs and I don't know where's the problem. Here is my code:
window.onload = () => {
"use strict";
let header = document.getElementsByTagName("header")[0];
let titleColor = document.getElementById("title_color");
let nav = document.getElementsByTagName("nav")[0];
let newColors = document.getElementById("new_colors");
let prompt = document.getElementById("prompt");
let easy = document.getElementById("easy");
let hard = document.getElementById("hard");
let active = document.getElementsByClassName("active")[0];
let colors = document.querySelectorAll("[id^=color]");
const initialize = () => {
let t = Math.floor(Math.random() * 5);
for (let i = 0; i < colors.length; i++) {
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
colors[i].style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}
titleColor.innerHTML = colors[t].style.backgroundColor;
addingEventHandlers(t);
}
const addingEventHandlers = t => {
for (let i = 0; i < colors.length; i++) {
colors[i].addEventListener("click", () => {
console.log(i);
if (t === i) {
header.style.backgroundColor = colors[t].style.backgroundColor;
for (let j = 0; j < nav.children.length; j++) {
if (nav.children[j] === active) {
nav.children[j].style.color = "rgb(FF, FF, FF)";
nav.children[j].style.backgroundColor = colors[t].style.backgroundColor;
} else {
nav.children[j].style.color = colors[t].style.backgroundColor;
nav.children[j].style.backgroundColor = "rgb(FF, FF, FF)";
}
}
for (let j = 0; j < colors.length; j++) {
colors[j].style.backgroundColor = colors[t].style.backgroundColor;
}
prompt.innerHTML = "Correct";
newColors.innerHTML = "Play Again";
newColors.addEventListener("click", () => initialize())
} else {
console.log(i);
colors[i].style.transitionProperty = "background-color";
colors[i].style.transitionDuration = "1s";
colors[i].style.transitionTimingFunction = "ease-in-out";
colors[i].style.backgroundColor = "rgb(0, 0, 0)";
prompt.innerHTML = "Try Again";
newColors.innerHTML = "New Colors";
newColors.addEventListener("click", () => initialize())
}
})
}
}
initialize();
}
* {
box-sizing: border-box;
}
body {
margin: 0;
text-transform: uppercase;
font-family:'Courier New', Courier, monospace;
font-weight: normal;
font-size: 100%;
text-align: center;
}
header {
color: white;
background-color: navy;
margin: 0;
}
header>h3 {
font-size: 2em;
margin: 0;
}
header>h1 {
font-size: 4em;
margin: 0;
}
nav {
background-color: white;
color: navy;
position: relative;
height: 38px;
}
nav>button {
background-color: white;
color: navy;
border: none;
font-size: 1.5em;
padding: 5px;
text-transform: uppercase;
}
#new_colors {
position: absolute;
left: 20%;
}
#easy {
position: absolute;
left: 62%;
}
#hard {
position: absolute;
left: 72%;
}
nav>button:not(.active):hover {
cursor: pointer;
background-color: navy;
color: white;
}
button.active {
cursor: pointer;
background-color: navy;
color: white;
border: none;
}
#container {
background-color: black;
display: grid;
grid-gap: 20px;
align-content: center;
justify-content: center;
width: 100%;
height: 792px;
}
[id^=color] {
border-radius: 10px;
background-color: white;
width: 200px;
height: 200px;
}
[id^=color]:hover {
cursor: pointer;
opacity: 0.9;
}
#color1 {
grid-area: 1 / 1 / 2 / 2;
}
#color2 {
grid-area: 1 / 2 / 2 / 3;
}
#color3 {
grid-area: 1 / 3 / 2 / 4;
}
#color4 {
grid-area: 2 / 1 / 3 / 2;
}
#color5 {
grid-area: 2 / 2 / 3 / 3;
}
#color6 {
grid-area: 2 / 3 / 3 / 4;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="color guessing game">
<meta name="description" content="color guessing game">
<meta name="author" content="Nick">
<link rel="stylesheet" href="color_guessing.css">
<script src="color_guessing.js"></script>
</head>
<body>
<header>
<h3>The Great</h3>
<h1 id="title_color"></h1>
<h3>Guessing Game</h3>
</header>
<nav>
<button id="new_colors">New Colors</button>
<button id="prompt"></button>
<button id="easy" >Easy</button>
<button id="hard" class="active">Hard</button>
</nav>
<div id="container">
<div id="color1"></div>
<div id="color2"></div>
<div id="color3"></div>
<div id="color4"></div>
<div id="color5"></div>
<div id="color6"></div>
</div>
</body>
</html>
Just like #Thomas said in the comments you need to check if there is an event already and add an event listener if there is none.
if (!colors[i].onclick) {
// your add event listener code goes here
}
You call addingEventHandlers from within initialise. This means that when initialise is called again (like when you start a new game) you will call addEventListener on the same element a second time, meaning you will call a handler twice when the event occurs. And this only gets worse as you call initialise again and again.
So move the call to addingEventHandlers outside of the initialise function body, so that it only gets called on page load, and then no more.

JS Can't update a value in HTML connected to a value in an array of objects

I'm trying to update the value inside an array of objects using this
syntax: array[objectindex].key = array[objectindex].key + 1;
on console.log work perfectly taking the value from the object, the problem is the value in the object isn't updated.
I'm trying to update SCORE BOARDS with a function inside MATCHING.
I use that value as a scoring point in HTML.
//-----------------CARDS DECK--------------------
var cards = [
{
rank:"Queen",
suit: "Hearts",
cardImage: "images/queen-of-hearts.png"
},
{
rank: "Queen",
suit: "Dimonds",
cardImage: "images/queen-of-diamonds.png"
},
{rank: "King",
suit: "Hearts",
cardImage: "images/king-of-hearts.png"
},
{
rank: "King",
suit: "Diamonds",
cardImage: "images/king-of-diamonds.png"
}
];
//-----------------SCORE BOARDS-----------------
var score = [
{
points:0,
parent: 'left-board',
side:"p1"
},
{
points:0,
parent:'right-board',
side:"ai"
}
];
var cardsInPlay = [];
//----------------CREATE THE GAMEBOARD-----------
var createBoard = function () {
for (var i=0; i < cards.length; i++) {
var cardElement = document.createElement('img');
cardElement.setAttribute('src','images/back.png');
cardElement.setAttribute('data-id',i);
cardElement.addEventListener('click',flipCard);
document.getElementById('game-board').appendChild(cardElement);
}
}
//--------------CREATE SCORE-------------------
var createScore = function () {
for (var i=0; i < score.length; i++) {
var scoreElement = document.createElement('div');
scoreElement.setAttribute('class','points');
scoreElement.setAttribute('id',score[i].side);
document.getElementById(score[i].parent).appendChild(scoreElement);
document.getElementById(score[i].side).innerHTML=score[i].points;
}
}
//----------------FLIPCARD----------------------
var flipCard = function () {
var cardId = this.getAttribute("data-id");
console.log("User flipped over " + cards[cardId].rank);
console.log(cards[cardId].suit);
console.log(cards[cardId].cardImage);
cardsInPlay.push(cards[cardId].rank);
this.setAttribute('src',cards[cardId].cardImage);
if (cardsInPlay.length === 2) {
setTimeout(checkForMatch,300);
//reset();
}
}
//----------------MATCHING------------------------
function checkForMatch() {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
score[0].points ++;
console.log(score[0]);
}
else {
alert("Sorry, try again.");
}
}
//----------------GAME RESET---------------------
var reset = function () {
for (var i=0; i < cards.length; i++) {
document.getElementsByTagName('img')[i].setAttribute('src','images/back.png');
}
cardsInPlay = [];
}
//##############---INVOKING----#####################
createScore();
createBoard();
//score[0].points =
console.log(score[0].points);
body {
text-align: center;
margin: 0;
}
h1 {
font-family: Raleway;
color: white;
letter-spacing: 1px;
font-weight: 400;
font-size: 45px;
margin: 0;
}
a {
font-family: Raleway;
letter-spacing: 1px;
font-weight: 400;
font-size: 18px;
border-bottom: 2px solid transparent;
}
a:hover {
border-bottom: 2px solid white;
}
h2 {
font-family: Raleway;
color: #0d2c40;
letter-spacing: 1px;
font-weight: 600;
font-size: 20;
}
p {
font-family: "Droid Serif";
line-height: 26px;
font-size: 18px;
}
header {
background-color: #F15B31;
padding: 30px 20px;
}
main {
width: auto;
margin: 35px auto;
}
nav {
background: #00A6B3;
padding:20px 0;
}
.navlink {
margin:0 20px;
color: white;
}
img {
margin: 20px 8px;
}
footer {
background-color:#0D2C40;
text-transform: uppercase;
padding: 0 20px;
color: white;
font-size: 14px;
letter-spacing: .08em;
font-weight: 500;
}
.copyright {
font-family: Raleway, sans-serif;
float: left;
}
.message{
font-family: Raleway, sans-serif;
float: right;
}
.clearfix:after {
visibility: hidden;
display: block;
content: " ";
clear: both;
height: 0;
font-size: 0;
padding: 0;
}
.name {
color:#F15B31;
font-weight: 700;
}
.point-board {
border-style: solid;
position: absolute;
width: 150px;
height: 150px;
border-radius: 90px;
line-height: 100px;
text-align: center;
font-family: Raleway;
}
#left-board {
top: 630px;
left: 70px;
}
#right-board {
top: 630px;
left: 1152px;
}
.points {
margin: -50px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Droid+Serif|Raleway:400,500,600,700" rel="stylesheet">
<title>Marco's memory game</title>
</head>
<body>
<header>
<h1>Marco's memory game</h1>
</header>
<nav>
<a class="navlink" href="#instructions">Instructions</a>
<a class="navlink" href="#facts">Game facts</a>
<a class="navlink" href="#game-board">Play!</a>
</nav>
<main>
<h2 id="instructions">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>
<h2 id="facts">Game's facts</h2>
<p>An other popular memory game is called "Kim's game. Kim's Game is a game or exercise played by Boy Scouts, Girl Scouts
and Girl Guides, and other children's groups.[1] The game develops a person's capacity to observe and remember
details. The name is derived from Rudyard Kipling's 1901 novel Kim, in which the hero, Kim, plays the game during
his training as a spy.
More info...
</p>
<div class="point-board" id="left-board">PLAYER
<div class="points" id= "p1"></div>
</div>
<h2>Play!</h2>
<div id="game-board" class="board clearfix"></div>
<div class="point-board" id="right-board">AI
<div class="points" id= "ai">00</div>
</div>
</main>
<footer class="clearfix">
<p class="copyright">Copyright 2017</p>
<p class="message">Created with ♥ by <span class="name"> GA </span></p>
</footer>
<script src="js/main.js"></script>
</body>
</html>
I'm not sure why your code isn't working, but you can use ++ to simplify that statement...
score[0].points++;
Solved!
function checkForMatch() {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
document.getElementById('p1').innerHTML=score[0].points + 1;
console.log(score[0]);
}
else {
alert("Sorry, try again.");
}
}

Categories

Resources