Javascript removeChild doesn't work as expected - javascript

I have a code that gets characters names and gender after clicking on film name. This information appears in modal window and my goal is to delete HTML element with characters every time I close modal, so if I select another film the new set of characters will appear, and the old one is already deleted.
The problem is that removeChild method doesn't work as expected. I've tried different variations including parentNode but nothing helped.
Here is the code:
window.addEventListener('DOMContentLoaded', function() {
let btn = document.querySelector('.sw-btn');
let content = document.querySelector('.content');
let modal = document.querySelector('.modal');
let modalBody = document.querySelector('.modal-body');
let closeBtn = document.querySelector('.close-btn');
let filmsList = document.createElement('ul');
let charsList = document.createElement('ol');
function getFilms() {
axios.get('https://swapi.co/api/films/').then(res => {
content.appendChild(filmsList);
for (var i = 0; i < res.data.results.length; i++) {
res.data.results.sort(function(a, b) {
let dateA = new Date(a.release_date),
dateB = new Date(b.release_date);
return dateA - dateB;
});
(function updateFilms() {
let addFilm = document.createElement('li');
filmsList.appendChild(addFilm);
let addFilmAnchor = document.createElement('a');
let addFilmId = document.createElement('p');
let addFilmCrawl = document.createElement('p');
let addFilmDirector = document.createElement('p');
let addFilmDate = document.createElement('p');
addFilmAnchor.textContent = res.data.results[i].title;
addFilmId.textContent = `Episode ID: ${res.data.results[i].episode_id}`;
addFilmCrawl.textContent = `Episode description: ${res.data.results[i].opening_crawl}`;
addFilmDirector.textContent = `Episode director: ${res.data.results[i].director}`;
addFilmDate.textContent = `Episode release date: ${res.data.results[i].release_date}`;
addFilm.append(addFilmAnchor, addFilmId, addFilmCrawl, addFilmDirector, addFilmDate);
})();
}
let links = document.getElementsByTagName('a');
for (let j = 0; j < links.length; j++) {
links[j].onclick = function() {
modal.style.display = 'block';
modalBody.appendChild(charsList);
let chars = res.data.results[j].characters;
for (let k = 0; k < chars.length; k++) {
const element = chars[k];
axios.get(element).then(res => {
let addChar = document.createElement('li');
charsList.appendChild(addChar);
let addCharName = document.createElement('p');
let addCharGender = document.createElement('p');
addCharName.textContent = `Character name: ${res.data.name}`;
addCharGender.textContent = `Character gender: ${res.data.gender}`;
addChar.append(addCharName, addCharGender);
})
}
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
console.log(modalBody.childNodes[0]);
// Problem is here
modalBody.removeChild(modalBody.childNodes[0]);
});
window.addEventListener('click', (e) => {
if (e.target == modal) {
modal.style.display = 'none';
console.log(modalBody.childNodes[0]);
modalBody.removeChild(modalBody.childNodes[0]);
}
})
}
}
}).catch(err => {
console.log("An error occured");
})
};
btn.addEventListener('click', getFilms);
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
window.addEventListener('click', (e) => {
if (e.target == modal) {
modal.style.display = 'none';
}
})
});
body {
max-height: 100vh;
padding: 0;
margin: 0;
font-family: Muli;
}
body::before {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Star_Wars_Logo.svg/1200px-Star_Wars_Logo.svg.png') no-repeat center / cover;
background-size: cover;
content: "";
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -2;
opacity: 0.1;
}
h1 {
text-align: center;
color: #660d41;
font-size: 3em;
margin-top: 10px;
letter-spacing: 1px;
}
main {
display: flex;
align-items: center;
flex-direction: column;
}
.content {
max-width: 55%;
overflow-y: scroll;
max-height: 75vh;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #f4f4f4;
margin: 20% auto;
width: 40%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.2);
animation: modalOpen 1s;
}
.modal-header {
background: coral;
padding: 15px;
color: white;
letter-spacing: 1px;
position: relative;
}
.modal-header h2 {
margin: 0;
}
.modal-body {
padding: 10px 20px;
}
.close-btn {
color: white;
float: right;
font-size: 30px;
position: absolute;
top: 0px;
right: 10px;
}
.close-btn:hover,
.close-btn:focus {
color: black;
text-decoration: none;
cursor: pointer;
transition: all 0.4s ease-in;
}
ul {
list-style-type: none;
padding: 10px 20px;
}
li {
border-bottom: 1px solid orangered;
margin-bottom: 30px;
}
li:last-child {
border-bottom: none;
margin-bottom: 0;
}
a {
font-size: 1.7em;
color: #b907d9;
cursor: pointer;
margin-bottom: 10px;
}
p {
font-size: 1.2rem;
color: #0f063f;
margin: 10px 0;
}
button {
padding: .5em 1.5em;
border: none;
color: white;
transition: all 0.2s ease-in;
background: #da2417;
border-radius: 20px;
font-size: 1em;
cursor: pointer;
margin-top: 15px;
}
button:focus {
outline: none;
}
button:hover {
background: #e7736b;
}
button:active {
box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.7) inset;
}
#keyframes modalOpen {
from {
opacity: 0
}
to {
opacity: 1
}
}
<link href="https://fonts.googleapis.com/css?family=Muli&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<h1>Star wars films</h1>
<main>
<div class="content"></div>
<div class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close-btn">×</span>
<h2>Episode Characters</h2>
</div>
<div class="modal-body"></div>
</div>
</div>
<button class="sw-btn">Find Films</button>
</main>
Any help would be appreciated.

The problem is that you are using the same ol element when appending the characters to the list, since you instantiate it at the beginning and re-use it later: let charsList = document.createElement('ol');
When you close the modal, you will remove that ol element from the modal, but you will not remove its content. When opening the modal again, the ol will be added again - with your old content.
If you move the declaration of charsList inside your onclick handler, it will work.
Also, you should register the close handlers of your modal only once. Otherwise, it will be called as often as you open your modal.
Demo:
window.addEventListener('DOMContentLoaded', function () {
let btn = document.querySelector('.sw-btn');
let content = document.querySelector('.content');
let modal = document.querySelector('.modal');
let modalBody = document.querySelector('.modal-body');
let closeBtn = document.querySelector('.close-btn');
let filmsList = document.createElement('ul');
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
console.log(modalBody.childNodes[0]);
modalBody.removeChild(modalBody.childNodes[0]);
});
window.addEventListener('click', (e) => {
if (e.target == modal) {
modal.style.display = 'none';
console.log(modalBody.childNodes[0]);
modalBody.removeChild(modalBody.childNodes[0]);
}
})
function getFilms() {
axios.get('https://swapi.co/api/films/').then(res => {
content.appendChild(filmsList);
for (var i = 0; i < res.data.results.length; i++) {
res.data.results.sort(function (a, b) {
let dateA = new Date(a.release_date),
dateB = new Date(b.release_date);
return dateA - dateB;
});
(function updateFilms() {
let addFilm = document.createElement('li');
filmsList.appendChild(addFilm);
let addFilmAnchor = document.createElement('a');
let addFilmId = document.createElement('p');
let addFilmCrawl = document.createElement('p');
let addFilmDirector = document.createElement('p');
let addFilmDate = document.createElement('p');
addFilmAnchor.textContent = res.data.results[i].title;
addFilmId.textContent = `Episode ID: ${res.data.results[i].episode_id}`;
addFilmCrawl.textContent = `Episode description: ${res.data.results[i].opening_crawl}`;
addFilmDirector.textContent = `Episode director: ${res.data.results[i].director}`;
addFilmDate.textContent = `Episode release date: ${res.data.results[i].release_date}`;
addFilm.append(addFilmAnchor, addFilmId, addFilmCrawl, addFilmDirector, addFilmDate);
})();
}
let links = document.getElementsByTagName('a');
for (let j = 0; j < links.length; j++) {
links[j].onclick = function () {
modal.style.display = 'block';
let charsList = document.createElement('ol');
modalBody.appendChild(charsList);
let chars = res.data.results[j].characters;
for (let k = 0; k < chars.length; k++) {
const element = chars[k];
axios.get(element).then(res => {
let addChar = document.createElement('li');
charsList.appendChild(addChar);
let addCharName = document.createElement('p');
let addCharGender = document.createElement('p');
addCharName.textContent = `Character name: ${res.data.name}`;
addCharGender.textContent = `Character gender: ${res.data.gender}`;
addChar.append(addCharName, addCharGender);
})
}
}
}
}).catch(err => {
console.log("An error occured");
})
};
btn.addEventListener('click', getFilms);
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
window.addEventListener('click', (e) => {
if (e.target == modal) {
modal.style.display = 'none';
}
})
});
body {
max-height: 100vh;
padding: 0;
margin: 0;
font-family: Muli;
}
body::before {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Star_Wars_Logo.svg/1200px-Star_Wars_Logo.svg.png') no-repeat center / cover;
background-size: cover;
content: "";
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -2;
opacity: 0.1;
}
h1 {
text-align: center;
color: #660d41;
font-size: 3em;
margin-top: 10px;
letter-spacing: 1px;
}
main {
display: flex;
align-items: center;
flex-direction: column;
}
.content {
max-width: 55%;
overflow-y: scroll;
max-height: 75vh;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #f4f4f4;
margin: 20% auto;
width: 40%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.2);
animation: modalOpen 1s;
}
.modal-header {
background: coral;
padding: 15px;
color: white;
letter-spacing: 1px;
position: relative;
}
.modal-header h2 {
margin: 0;
}
.modal-body {
padding: 10px 20px;
}
.close-btn {
color: white;
float: right;
font-size: 30px;
position: absolute;
top: 0px;
right: 10px;
}
.close-btn:hover,
.close-btn:focus {
color: black;
text-decoration: none;
cursor: pointer;
transition: all 0.4s ease-in;
}
ul {
list-style-type: none;
padding: 10px 20px;
}
li {
border-bottom: 1px solid orangered;
margin-bottom: 30px;
}
li:last-child {
border-bottom: none;
margin-bottom: 0;
}
a {
font-size: 1.7em;
color: #b907d9;
cursor: pointer;
margin-bottom: 10px;
}
p {
font-size: 1.2rem;
color: #0f063f;
margin: 10px 0;
}
button {
padding: .5em 1.5em;
border: none;
color: white;
transition: all 0.2s ease-in;
background: #da2417;
border-radius: 20px;
font-size: 1em;
cursor: pointer;
margin-top: 15px;
}
button:focus {
outline: none;
}
button:hover {
background: #e7736b;
}
button:active {
box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.7) inset;
}
#keyframes modalOpen {
from {
opacity: 0
}
to {
opacity: 1
}
}
<link href="https://fonts.googleapis.com/css?family=Muli&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<h1>Star wars films</h1>
<main>
<div class="content"></div>
<div class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close-btn">×</span>
<h2>Episode Characters</h2>
</div>
<div class="modal-body"></div>
</div>
</div>
<button class="sw-btn">Find Films</button>
</main>

Do this charsList.innerText = ''; when click close button.
When you call removeChild you take off the <ol> from modalbody in UI. You can see the modalBody is empty after clicking close button.
But you already store the <ol> element in js variable by let charsList = document.createElement('ol'); so the ol element itself doesn't change actually.
The <li> element still inside the <ol>. Then you add more new <li> and put it back to modalBody.
My solution is remove all element in <ol> when clicking close button.

Related

Javascript Improve collapsing element

I have created this toggle script which works well but I need to improve it so that onclick, any previously collapsed (i.e. open) subcats would simultaneously close and only the one clicked should collapse (i.e. open).
var collapse = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < collapse.length; i++) {
collapse[i].addEventListener("click", function() {
this.classList.toggle("activeCollapse");
var content = this.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
.catColumn {
width: 400px;
margin: 0 auto;
}
.collapsible {
width: 100%;
padding: 14px 8px;
margin-top: 10px;
color: #5a2e0f;
background-color: #fff;
border: 1px solid #c1bfbf;
outline: none;
border-radius: 6px;
}
.collapsible:hover {
background-color: #efdac6;
}
.collapsible:after {
float: right;
content: '\002B';
color: #5a2e0f;
font-size: 1.8em;
margin-left: 5px;
cursor: pointer;
line-height: 26px;
}
.activeCollapse {
background-color: #efdac6;
border-radius: 0;
border-bottom: 0px;
}
.activeCollapse:after {
content: "\2212";
}
/**/
ul.subcats {
width: 100%;
max-height: 0;
transition: max-height 1s ease-out;
overflow: hidden;
font-size: 13px;
}
ul.subcats li {
padding: 12px;
}
<div class="catColumn">
<div class="collapsible">cat1</div>
<ul class="subcats">
<li>subcat1</li>
<li>subcat2</li>
</ul>
<div class="collapsible">cat2</div>
<ul class="subcats">
<li>subcat3</li>
<li>subcat4</li>
</ul>
</div>
var collapse = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < collapse.length; i++) {
collapse[i].addEventListener("click", function() {
this.classList.toggle("activeCollapse");
for (j = 0; j < collapse.length; j++) {
this.classList.remove("activeCollapse");
if(j!=i)
collapse[j].nextElementSibling.style.maxHeight = null;
var content = this.nextElementSibling;
}
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
.catColumn {
width: 400px;
margin: 0 auto;
}
.collapsible {
width: 100%;
padding: 14px 8px;
margin-top: 10px;
color: #5a2e0f;
background-color: #fff;
border: 1px solid #c1bfbf;
outline: none;
border-radius: 6px;
}
.collapsible:hover {
background-color: #efdac6;
}
.collapsible:after {
float: right;
content: '\002B';
color: #5a2e0f;
font-size: 1.8em;
margin-left: 5px;
cursor: pointer;
line-height: 26px;
}
.activeCollapse {
background-color: #efdac6;
border-radius: 0;
border-bottom: 0px;
}
.activeCollapse:after {
content: "\2212";
}
/**/
ul.subcats {
width: 100%;
max-height: 0;
transition: max-height 1s ease-out;
overflow: hidden;
font-size: 13px;
}
ul.subcats li {
padding: 12px;
}
<div class="catColumn">
<div class="collapsible">cat1</div>
<ul class="subcats">
<li>subcat1</li>
<li>subcat2</li>
</ul>
<div class="collapsible">cat2</div>
<ul class="subcats">
<li>subcat3</li>
<li>subcat4</li>
</ul>
</div>
First, loop through the open elements and remove the class and set max height to null. Then do your normal code.
I also changed your event Listener so you only have one instead of one for each element.
var collapse = document.querySelector(".catColumn");
collapse.addEventListener("click", function(e) {
let el = e.target;
let hideSelf = (el.className.indexOf("activeCollapse") > 0);
if (el.className.indexOf("collapsible") > -1) {
let shown = document.querySelectorAll(".activeCollapse");
shown.forEach(function(activeEl) {
activeEl.classList.remove("activeCollapse");
activeEl.nextElementSibling.style.maxHeight = null;
});
if (hideSelf == false) {
el.classList.toggle("activeCollapse");
var content = el.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
}
}
});
.catColumn {
width: 400px;
margin: 0 auto;
}
.collapsible {
width: 100%;
padding: 14px 8px;
margin-top: 10px;
color: #5a2e0f;
background-color: #fff;
border: 1px solid #c1bfbf;
outline: none;
border-radius: 6px;
}
.collapsible:hover {
background-color: #efdac6;
}
.collapsible:after {
float: right;
content: '\002B';
color: #5a2e0f;
font-size: 1.8em;
margin-left: 5px;
cursor: pointer;
line-height: 26px;
}
.activeCollapse {
background-color: #efdac6;
border-radius: 0;
border-bottom: 0px;
}
.activeCollapse:after {
content: "\2212";
}
/**/
ul.subcats {
width: 100%;
max-height: 0;
transition: max-height 1s ease-out;
overflow: hidden;
font-size: 13px;
}
ul.subcats li {
padding: 12px;
}
<div class="catColumn">
<div class="collapsible">cat1</div>
<ul class="subcats">
<li>subcat1</li>
<li>subcat2</li>
</ul>
<div class="collapsible">cat2</div>
<ul class="subcats">
<li>subcat3</li>
<li>subcat4</li>
</ul>
</div>
var parentDiv = document.getElementsByClassName("catColumn")[0];
parentDiv.addEventListener("click",function(e){
let current= e.target;
var collapse = document.getElementsByClassName("collapsible");
let toExpand = !current.nextElementSibling.style.maxHeight ;
for (let i = 0; i < collapse.length; i++) {
var content = collapse[i].nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
collapse[i].classList.toggle("activeCollapse");
}
}
let toToggle = current.nextElementSibling;
if(toExpand ){
toToggle.style.maxHeight = content.scrollHeight + "px";
current.classList.toggle("activeCollapse");
}
});
.catColumn {
width: 400px;
margin: 0 auto;
}
.collapsible {
width: 100%;
padding: 14px 8px;
margin-top: 10px;
color: #5a2e0f;
background-color: #fff;
border: 1px solid #c1bfbf;
outline: none;
border-radius: 6px;
}
.collapsible:hover {
background-color: #efdac6;
}
.collapsible:after {
float: right;
content: '\002B';
color: #5a2e0f;
font-size: 1.8em;
margin-left: 5px;
cursor: pointer;
line-height: 26px;
}
.activeCollapse {
background-color: #efdac6;
border-radius: 0;
border-bottom: 0px;
}
.activeCollapse:after {
content: "\2212";
}
/**/
ul.subcats {
width: 100%;
max-height: 0;
transition: max-height 1s ease-out;
overflow: hidden;
font-size: 13px;
}
ul.subcats li {
padding: 12px;
}
<div class="catColumn">
<div class="collapsible">cat1</div>
<ul class="subcats">
<li>subcat1</li>
<li>subcat2</li>
</ul>
<div class="collapsible">cat2</div>
<ul class="subcats">
<li>subcat3</li>
<li>subcat4</li>
</ul>
</div>

How to make modal window accurately reflect contents of each note in a note-taking app?

I am fairly new to javascript, and am working on a note-taking app to practice some things I have learned so far. It all works fine, however, when I click on the Read More button to view overflow text of the note, it displays the text from the most recent note, as opposed to the note I click Read More on. I want the entire text of a particular note to be displayed when its corresponding Read More button is pressed. Am I overthinking this? I think some kind of implementation of for...of, or for loops may help me achieve this outcome. This is a link to my codepen: https://codepen.io/oliverc96/pen/xxdZYrr
const addNote = document.querySelector('.add-note');
const newNote = document.querySelector('#new-note');
const noteFeed = document.querySelector('#note-feed');
let modalBg = document.createElement('div');
let modalWindow = document.createElement('div');
let exitSymbol = document.createElement('i');
let modalText = document.createElement('p');
function expandNote() {
modalWindow.classList.add('enterAnimation');
modalBg.style.visibility = 'visible';
exitSymbol.addEventListener('click', () => {
modalBg.style.visibility = 'hidden';
modalWindow.classList.remove('enterAnimation');
})
}
function createNote() {
const noteContainer = document.createElement('div');
noteContainer.classList.add('containerStyle');
let noteHeader = document.createElement('h1');
const noteNum = noteFeed.childElementCount;
noteHeader.innerText = `Note #${noteNum + 1}`;
noteHeader.classList.add('headerStyle');
noteContainer.append(noteHeader);
let noteText = document.createElement('p');
noteText.innerText = `${newNote.value}`;
noteText.classList.add('paraStyle');
noteContainer.append(noteText);
let readMore = document.createElement('button');
readMore.innerText = 'Read More';
readMore.classList.add('btnStyle');
noteContainer.append(readMore);
noteFeed.append(noteContainer);
readMore.addEventListener('click', expandNote);
modalBg.classList.add('modal-bg');
modalWindow.classList.add('modal-window');
exitSymbol.className = 'far fa-times-circle';
exitSymbol.classList.add('exitSymbol');
modalWindow.append(exitSymbol);
modalText.classList.add('fullTextStyle');
modalText.innerText = `${noteText.innerText}`;
modalWindow.append(modalText);
modalBg.append(modalWindow);
noteContainer.append(modalBg);
newNote.value = '';
}
addNote.addEventListener('click', createNote);
newNote.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
createNote();
}
})
Actually your modalText will always store the latest value according to your code. You can follow the following steps to solve this.
Attach an data-attribute to that noteText.
When click on read more pass the id of that specific note.
Now just show the innerText of that selected item. You can use querySelector to get the element using data-attribute.
You can check my implementation.
console.clear();
const addNote = document.querySelector('.add-note');
const newNote = document.querySelector('#new-note');
const noteFeed = document.querySelector('#note-feed');
let modalBg = document.createElement('div');
let modalWindow = document.createElement('div');
let exitSymbol = document.createElement('i');
let modalText = document.createElement('p');
function expandNote(noteContainer, noteNum) {
return function () {
modalWindow.classList.add('enterAnimation');
modalBg.style.visibility = 'visible';
exitSymbol.addEventListener('click', () => {
modalBg.style.visibility = 'hidden';
modalWindow.classList.remove('enterAnimation');
})
const data = document.querySelector(`[data-id='${noteNum}']`).innerText;
showMoreModal(noteContainer, data);
}
}
function showMoreModal(noteContainer, data) {
modalBg.classList.add('modal-bg');
modalWindow.classList.add('modal-window');
exitSymbol.className = 'far fa-times-circle';
exitSymbol.classList.add('exitSymbol');
modalWindow.append(exitSymbol);
modalText.classList.add('fullTextStyle');
modalText.innerText = `${data}`;
modalWindow.append(modalText);
modalBg.append(modalWindow);
noteContainer.append(modalBg);
}
function createNote() {
const noteContainer = document.createElement('div');
noteContainer.classList.add('containerStyle');
let noteHeader = document.createElement('h1');
const noteNum = noteFeed.childElementCount;
noteHeader.innerText = `Note #${noteNum + 1}`;
noteHeader.classList.add('headerStyle');
noteContainer.append(noteHeader);
let noteText = document.createElement('p');
noteText.innerText = `${newNote.value}`;
noteText.classList.add('paraStyle');
noteText.setAttribute('data-id', noteNum);
noteContainer.append(noteText);
let readMore = document.createElement('button');
readMore.innerText = 'Read More';
readMore.classList.add('btnStyle');
noteContainer.append(readMore);
noteFeed.append(noteContainer);
readMore.addEventListener('click', expandNote(noteContainer, noteNum));
newNote.value = '';
}
addNote.addEventListener('click', createNote);
newNote.addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
createNote();
}
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: 'Montserrat', sans-serif;
}
#wrapper {
width: 1600px;
height: 100vh;
margin: auto;
text-align: center;
}
h1 {
font-size: 100px;
margin-top: 20px;
font-weight: 500;
}
h2 {
font-size: 50px;
font-weight: 400;
margin-top: 10px;
}
#add-new-note {
color: rgb(0, 153, 153);
}
textarea {
width: 1500px;
margin-top: 30px;
height: 60px;
border-radius: 6px;
padding: 20px;
font-size: 18px;
}
textarea:focus {
outline-color: black;
}
.add-note {
font-size: 20px;
width: 180px;
height: 50px;
border-radius: 6px;
margin-top: 30px;
background-color: rgb(0, 153, 153);
color: white;
border-style: solid;
border-color: rgb(0, 102, 102);
}
.add-note:hover {
background-color: rgb(0, 128, 128);
cursor: pointer;
}
#note-feed {
background-color: rgb(0, 153, 153);
height: 500px;
margin-top: 25px;
width: 1500px;
border-radius: 6px;
display: flex;
overflow: scroll;
flex-wrap: wrap;
padding: 20px 10px;
margin-left: 50px;
}
.containerStyle {
display: flex;
flex-direction: column;
justify-content: space-around;
background-color: rgb(169, 169, 214);
height: 48%;
width: 31%;
margin-right: 11px;
margin-left: 20px;
border-radius: 6px;
margin-bottom: 20px;
overflow: hidden;
padding: 0 28px;
padding-bottom: 15px;
text-align: left;
}
.headerStyle {
font-size: 30px;
}
.paraStyle {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
font-size: 18px;
text-overflow: ellipsis;
overflow: hidden;
}
.btnStyle {
font-size: 20px;
width: 150px;
height: 40px;
border-radius: 6px;
background-color: rgb(255, 128, 128);
color: white;
border-style: solid;
border-color: rgb(255, 77, 77);
align-self: left;
}
.btnStyle:hover {
background-color: rgb(255, 102, 102);
cursor: pointer;
}
.modal-bg {
z-index: 1;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0,0,0,0.5);
color: white;
display: flex;
justify-content: center;
align-items: center;
visibility: hidden;
overflow: scroll;
}
.modal-window {
border-radius: 6px;
background: white;
width: 70%;
min-height: 30%;
max-height: 70%;
overflow: scroll;
display: flex;
justify-content: flex-start;
align-items: flex-start;
}
.enterAnimation {
animation-name: fadeInDown;
animation-duration: 1s;
}
#keyframes fadeInDown {
0% {
opacity: 0;
transform: translateY(-200px);
}
100% {
opacity: 1;
}
}
.exitSymbol {
color: rgb(0, 128, 128);
font-size: 30px;
margin: 20px 20px;
}
.exitSymbol:hover {
cursor: pointer;
opacity: 0.8;
}
.fullTextStyle {
color: black;
width: 90%;
height: 80%;
text-align: left;
margin-top: 60px;
margin-bottom: 30px;
font-size: 18px;
}
<html>
<head>
<title> Note Taker </title>
<link type="text/css" href="notes.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#100;200;300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<h1> Note Taker </h1>
<h2 id="add-new-note"> Add A New Note: </h2>
<textarea id="new-note" name="note-box" placeholder="Write your note here"></textarea>
<button class="add-note"> Add Note </button>
<div id="note-feed">
</div>
</div>
<script src="notes.js"></script>
<script src="https://kit.fontawesome.com/6fc6f370ca.js" crossorigin="anonymous"></script>
</body>
</html>

Blur Image JavaScript

I have started making a blur image so when you click the button "Blur Image", it will blur image but there are some errors showing on Console.Log and I have been trying to solve it but didn't had success.
let btn = document.querySelector('.btnbl')[0];
let img = document.querySelector('img')[0];
c = 0;
function coverImage () {
if( c === 0) {
btn.innerHTML = 'Blur Image';
img.style.filter = 'blur(0)';
c = 1;
} else {
btn.innerHTML = 'Unblur Image';
img.style.filter = 'blur(24px)';
c = 0;
}
}
.blur{
margin-top: 20px;
display: flex;
justify-content: center;
}
.blur img{
width: 730px;
height: 520px;
filter: blur(0px);
}
.btnbl{
position: absolute;
top: 45px;
right: 452px;
padding: 7px;
background-color: darkslategray;
border-radius: 5px solid yellow;
font-size: 20px;
color: white;
cursor: pointer;
font-family: sans-serif;
}
<div class="blur">
<img src="https://4.bp.blogspot.com/_EZ16vWYvHHg/TFBW_zN6oaI/AAAAAAAAQd4/8UxrcXLQ5js/s1600/www.idool.net-Perrito.jpg">
<button onclick="coverImage()" class="btnbl">Blur Image</button>
</div>
document.querySelector returns a single element so no need to access the elements like it returns an array by using []. and make c=1 before calling the function because originally it is un-blurred
let btn = document.querySelector('.btnbl');
let img = document.querySelector('img');
c = 1;
function coverImage () {
if( c === 0) {
btn.innerHTML = 'Blur Image';
img.style.filter = 'blur(0)';
c = 1;
} else {
btn.innerHTML = 'Unblur Image';
img.style.filter = 'blur(24px)';
c = 0;
}
}
.blur{
margin-top: 20px;
display: flex;
justify-content: center;
}
.blur img{
width: 730px;
height: 520px;
filter: blur(0px);
}
.btnbl{
position: absolute;
top: 45px;
right: 452px;
padding: 7px;
background-color: darkslategray;
border-radius: 5px solid yellow;
font-size: 20px;
color: white;
cursor: pointer;
font-family: sans-serif;
}
<div class="blur">
<img src="https://4.bp.blogspot.com/_EZ16vWYvHHg/TFBW_zN6oaI/AAAAAAAAQd4/8UxrcXLQ5js/s1600/www.idool.net-Perrito.jpg">
<button onclick="coverImage()" class="btnbl">Blur Image</button>
</div>
querySelector() returns only one element, so no need to reference it as an array.
Just take out the indexes for the variables like so:
let btn = document.querySelector('.btnbl');
let img = document.querySelector('img');
let btn = document.querySelector('.btnbl');
let img = document.querySelector('img');
c = 0;
function coverImage () {
if( c === 0) {
btn.innerHTML = 'Blur Image';
img.style.filter = 'blur(0)';
c = 1;
} else {
btn.innerHTML = 'Unblur Image';
img.style.filter = 'blur(24px)';
c = 0;
}
}
.blur{
margin-top: 20px;
display: flex;
justify-content: center;
}
.blur img{
width: 730px;
height: 520px;
filter: blur(0px);
}
.btnbl{
position: absolute;
top: 45px;
right: 452px;
padding: 7px;
background-color: darkslategray;
border-radius: 5px solid yellow;
font-size: 20px;
color: white;
cursor: pointer;
font-family: sans-serif;
}
<div class="blur">
<img src="https://4.bp.blogspot.com/_EZ16vWYvHHg/TFBW_zN6oaI/AAAAAAAAQd4/8UxrcXLQ5js/s1600/www.idool.net-Perrito.jpg">
<button onclick="coverImage()" class="btnbl">Blur Image</button>
</div>

Restart Simon Game in javascript

How I can make the game restart from the beginning by clicking start button except reloading the whole page?
The problem occurs because when user clicks Start playGame function is called, but the a previous instance of playGame function is still running. I even thought about to kill a previous instance of function but in JS it can not be implemented except using webworker.terminate().
Here's the code:
document.addEventListener("DOMContentLoaded", function() {
'use strict';
var checkOn = document.querySelector("input[type=checkbox]");
var gameCount = document.getElementsByClassName("innerCount")[0];
var startButton = document.getElementById("innerStart");
var strictButton = document.getElementById("strictButton");
var strictInd = document.getElementById("strictIndicator");
var strictMode = false;
var soundArray = document.getElementsByTagName("audio");
var buttons = document.querySelectorAll(".bigButton");
var buttonArray = [].slice.call(buttons, 0);
checkOn.addEventListener("change", function() {
if (checkOn.checked) {
gameCount.innerHTML = "--";
} else {
gameCount.innerHTML = "";
}
});
strictButton.addEventListener("click", function() {
if (checkOn.checked) {
strictMode = !strictMode;
strictMode ? strictInd.style.backgroundColor = "#FF0000" :
strictInd.style.backgroundColor = "#850000";
}
});
function getRandArray() {
var array = [];
for (var i = 0; i < 22; i++) {
array[i] = Math.floor(Math.random() * 4);
}
return array;
}
startButton.addEventListener("click", function() {
if (checkOn.checked) {
var level = 0;
var randIndexArr = getRandArray();
sleep(700).then(function() {
playGame(randIndexArr, level);
});
}
});
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time)
})
}
function checkButton(randIndexArr, counter) {
var indexButton = 0;
var checker = function checker(e) {
var clickedButtonId = e.target.dataset.sound;
lightenButton(clickedButtonId);
if (+(clickedButtonId) === randIndexArr[indexButton]) {
if (indexButton === counter) {
counter++;
for (let i = 0; i < 4; i++) {
buttonArray[i].removeEventListener("click", checker, false)
}
sleep(2000).then(function() {
playGame(randIndexArr, counter);
});
}
indexButton++;
} else {
gameCount.innerHTML = "--";
if (strictMode) {
indexButton = 0;
counter = 0;
} else {
indexButton = 0;
}
for (let i = 0; i < 4; i++) {
buttonArray[i].removeEventListener("click", checker, false)
}
sleep(2000).then(function() {
playGame(randIndexArr, counter);
});
}
};
for (var i = 0; i < 4; i++) {
buttonArray[i].addEventListener("click", checker, false)
}
}
function playGame(randIndexArr, counter) {
if (counter === 22) {
return;
}
//Show the level of the Game
gameCount.innerHTML = counter + 1;
//Light and play user's input then check if input is correct
randIndexArr.slice(0, counter + 1).reduce(function(promise, div, index) {
return promise.then(function() {
lightenButton(div);
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, 1000);
})
})
}, Promise.resolve()).then(function() {
checkButton(randIndexArr, counter);
});
}
function lightenButton(id) {
var lightColorsArr = ["liteGreen", "liteRed", "liteYell", "liteBlue"];
soundArray[id].play();
buttonArray[id].classList.add(lightColorsArr[id]);
sleep(500).then(function() {
buttonArray[id].classList.remove(lightColorsArr[id])
});
}
});
#font-face {
font-family: myDirector;
src: url('https://raw.githubusercontent.com/Y-Taras/FreeCodeCamp/master/Simon/fonts/myDirector-Bold.otf');
}
body {
background-color: #5f5f5f;
}
#outerCircle {
display: flex;
flex-wrap: wrap;
margin: 0 auto;
width: 560px;
border: 2px dotted grey;
position: relative;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.bigButton {
height: 250px;
width: 250px;
border: solid #464646;
transition: all 1s;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: background-color 0.5s ease;
}
#greenButton {
background-color: rgb(9, 174, 37);
border-radius: 100% 0 0 0;
border-width: 20px 10px 10px 20px;
}
.liteGreen#greenButton {
background-color: #86f999;
}
#redButton {
background-color: rgb(174, 9, 15);
border-radius: 0 100% 0 0;
border-width: 20px 20px 10px 10px;
}
.liteRed#redButton {
background-color: #f9868a;
}
#yellowButton {
background-color: rgb(174, 174, 9);
border-radius: 0 0 0 100%;
border-width: 10px 10px 20px 20px;
}
.liteYell#yellowButton {
background-color: #f9f986;
}
#blueButton {
background-color: rgb(9, 37, 174);
border-radius: 0 0 100% 0;
border-width: 10px 20px 20px 10px;
}
.liteBlue#blueButton {
background-color: #8699f9;
}
div#innerCircle {
border: 15px solid #464646;
border-radius: 50%;
position: absolute;
top: 25%;
right: 25%;
background-color: #c4c7ce;
}
div.additionalBorder {
margin: 4px;
border-radius: 50%;
height: 242px;
width: 242px;
overflow: hidden;
}
p#tradeMark {
margin: auto;
height: 104px;
text-align: center;
font-size: 68px;
font-family: myDirector;
color: #c4c7ce;
background-color: black;
border-color: antiquewhite;
line-height: 162px;
}
span#reg {
font-size: 12px;
}
.partition {
height: 6px;
}
.buttons {
height: 128px;
border-radius: 0 0 128px 128px;
border: 2px solid black;
}
/* Start and Strict buttons*/
table {
margin-left: 5px;
}
td {
text-align: center;
width: auto;
padding: 2px 10px;
vertical-align: bottom;
}
div.innerCount {
width: 54px;
height: 40px;
background-color: #34000e;
color: crimson;
border-radius: 11px;
font-size: 28px;
line-height: 42px;
text-align: center;
font-family: 'Segment7Standard', italic;
}
button#innerStart {
width: 27px;
height: 27px;
border: 4px solid #404241;
border-radius: 50%;
background: #a50005;
box-shadow: 0 0 3px gray;
cursor: pointer;
}
div.strict {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
button#strictButton {
width: 27px;
height: 27px;
border: 4px solid #404241;
border-radius: 50%;
background: yellow;
box-shadow: 0 0 3px gray;
cursor: pointer;
}
div#strictIndicator {
width: 6px;
height: 6px;
margin-bottom: 2px;
background-color: #850000;
border-radius: 50%;
border: 1px solid #5f5f5f;
}
#switcher {
display: flex;
justify-content: center;
align-items: center;
}
.labels {
font-family: 'Roboto', sans-serif;
margin: 4px;
}
/* toggle switch */
.checkbox > input[type=checkbox] {
visibility: hidden;
}
.checkbox {
display: inline-block;
position: relative;
width: 60px;
height: 30px;
border: 2px solid #424242;
}
.checkbox > label {
position: absolute;
width: 30px;
height: 26px;
top: 2px;
right: 2px;
background-color: #a50005;
cursor: pointer;
}
.checkbox > input[type=checkbox]:checked + label {
right: 28px;
}
<div id="outerCircle">
<div class="bigButton" id="greenButton" data-sound="0">
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"></audio>
</div>
<div class="bigButton" id="redButton" data-sound="1">
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"></audio>
</div>
<div class="bigButton" id="yellowButton" data-sound="2">
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"></audio>
</div>
<div class="bigButton" id="blueButton" data-sound="3">
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"></audio>
</div>
<div id="innerCircle">
<div class="additionalBorder">
<p id="tradeMark">simon<span id="reg">®</span>
</p>
<div class="partition"></div>
<div class="buttons">
<table>
<tr class="firstRow">
<td>
<div class="innerCount"></div>
</td>
<td>
<button type="button" id="innerStart"></button>
</td>
<td>
<div class="strict">
<div id="strictIndicator"></div>
<button type="button" id="strictButton"></button>
</div>
</td>
</tr>
<tr class="labels">
<td>
<div id="countLabel">COUNT</div>
</td>
<td>
<div id="startLabel">START</div>
</td>
<td>
<div id="strictLabel">STRICT</div>
</td>
</tr>
</table>
<div id="switcher">
<span class="labels">ON</span>
<div class="checkbox">
<input id="checkMe" type="checkbox">
<label for="checkMe"></label>
</div>
<span class="labels">OFF</span>
</div>
</div>
</div>
</div>
</div>
I didn't dig super deep into your code, but it looks like the crux of it is you're using setTimeout(), and that timeout may still be running when you restart.
What you need to do is store the return value of setTimeout() which is actually an id you can then pass to clearTimeout(), which will stop that timeout.
So, on your sleep() function, store the id:
function sleep(time) {
return new Promise(resolve => {
this.timeoutId = setTimeout(resolve, time)
});
}
And when you go to restart your game:
// ...
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
//...
And then also just make sure you don't have any other code that will get more than two timeouts running at the same time (or you'll lose one of the ids).

How to make the simon game work properly

I'm working on the "Simon Game" project.
I want it to lighten buttons in the proper sequence. But now by far the code works properly until the 2-nd level.
If I am right the checkButton(randIndexArr, counter) should be included to the promise, so that if counter === index then it should call checkButton and maybe there are some more errors that I missed.
Here's a link with the video: How the code should work to be more clear Zipline: Build a Simon Game
and here is my code:
document.addEventListener("DOMContentLoaded", function () {
'use strict';
var checkOn = document.querySelector("input[type=checkbox]");
var gameCount = document.getElementsByClassName("innerCount")[0];
var startButton = document.getElementById("innerStart");
var strictButton = document.getElementById("strictButton");
var strictInd = document.getElementById("strictIndicator");
var strictMode = false;
var soundArray = document.getElementsByTagName("audio");
var buttons = document.querySelectorAll(".bigButton");
var buttonArray = [].slice.call(buttons, 0);
checkOn.addEventListener("change", function () {
if (checkOn.checked) {
gameCount.innerHTML = "--";
} else {
gameCount.innerHTML = "";
}
});
strictButton.addEventListener("click", function () {
strictMode = !strictMode;
strictMode ? strictInd.style.backgroundColor = "#FF0000" :
strictInd.style.backgroundColor = "#850000";
});
function getRandArray() {
var array = [];
for (var i = 0; i < 22; i++) {
array[i] = Math.floor(Math.random() * 4);
}
document.getElementsByClassName("randArray")[0].innerHTML = array;
return array;
}
startButton.addEventListener("click", function () {
var level = 0;
var randIndexArr = getRandArray();
playGame(randIndexArr, level);
});
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time)
})
}
function checkButton(randIndexArr, counter) {
console.log('checkButton');
var checker = function checker(e) {
var clickedButtonId = e.target.dataset.sound;
lightenButton(clickedButtonId);
sleep(1000);
for (let index = 0; index <= counter; index++) {
if (+(clickedButtonId) === randIndexArr[index]) {
if (index === counter) {
console.log('checking passed - next level :', (counter + 1));
counter++;
for (var i = 0; i < 4; i++) {
buttonArray[i].removeEventListener("click", checker, false)
}
playGame(randIndexArr, counter);
}
}
}
}
;
for (var i = 0; i < 4; i++) {
buttonArray[i].addEventListener("click", checker, false)
}
}
function playGame(randIndexArr, counter) {
if (counter === 22) {
return;
}
//Show the level of the Game
gameCount.innerHTML = counter + 1;
//Light and play random buttons according to the level
//Light and play user's input then check if input is correct
randIndexArr.slice(0, counter + 1).reduce(function (promise, div, index) {
return promise.then(function () {
console.log("slice reduce");
lightenButton(div);
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("reduce Resolve");
}, 1000);
})
})
}, Promise.resolve()).then(function (value) {
console.log(value);
checkButton(randIndexArr, counter);
});
}
function lightenButton(id) {
var lightColorsArr = ["liteGreen", "liteRed", "liteYell", "liteBlue"];
var promise = new Promise((resolve, reject) => {
soundArray[id].play();
buttonArray[id].classList.add(lightColorsArr[id]);
setTimeout(function () {
resolve("lighten");
}, 500);
});
promise.then(function (value) {
console.log(value);
buttonArray[id].classList.remove(lightColorsArr[id]);
});
}
});
#font-face {
font-family: myDirector;
src: url('https://raw.githubusercontent.com/Y-Taras/FreeCodeCamp/master/Simon/fonts/myDirector-Bold.otf');
}
#outerCircle {
display: flex;
flex-wrap: wrap;
margin: 0 auto;
width: 560px;
border: 2px dotted grey;
position: relative;
}
.bigButton {
height: 250px;
width: 250px;
border: solid #464646;
transition: all 1s;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: background-color 0.5s ease;
}
#greenButton {
background-color: rgb(9, 174, 37);
border-radius: 100% 0 0 0;
border-width: 20px 10px 10px 20px;
}
.liteGreen#greenButton {
background-color: #86f999;
}
#redButton {
background-color: rgb(174, 9, 15);
border-radius: 0 100% 0 0;
border-width: 20px 20px 10px 10px;
}
.liteRed#redButton {
background-color: #f9868a;
}
#yellowButton {
background-color: rgb(174, 174, 9);
border-radius: 0 0 0 100%;
border-width: 10px 10px 20px 20px;
}
.liteYell#yellowButton {
background-color: #f9f986;
}
#blueButton {
background-color: rgb(9, 37, 174);
border-radius: 0 0 100% 0;
border-width: 10px 20px 20px 10px;
}
.liteBlue#blueButton {
background-color: #8699f9;
}
div#innerCircle {
border: 15px solid #464646;
border-radius: 50%;
position: absolute;
top: 25%;
right: 25%;
background-color: #c4c7ce;
}
div.additionalBorder {
margin: 4px;
border-radius: 50%;
height: 242px;
width: 242px;
overflow: hidden;
}
p#tradeMark {
margin: auto;
height: 104px;
text-align: center;
font-size: 68px;
font-family: myDirector;
color: #c4c7ce;
background-color: black;
border-color: antiquewhite;
line-height: 162px;
}
span#reg {
font-size: 12px;
}
.partition {
height: 6px;
}
.buttons {
height: 128px;
border-radius: 0 0 128px 128px;
border: 2px solid black;
}
/* Start and Strict buttons*/
table {
margin-left: 5px;
}
td {
text-align: center;
width: auto;
padding: 2px 10px;
vertical-align: bottom;
}
div.innerCount {
width: 54px;
height: 40px;
background-color: #34000e;
color: crimson;
border-radius: 11px;
font-size: 28px;
line-height: 42px;
text-align: center;
font-family: 'Segment7Standard', italic;
}
button#innerStart {
width: 27px;
height: 27px;
border: 4px solid #404241;
border-radius: 50%;
background: #a50005;
box-shadow: 0 0 3px gray;
cursor: pointer;
}
div.strict {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
button#strictButton {
width: 27px;
height: 27px;
border: 4px solid #404241;
border-radius: 50%;
background: yellow;
box-shadow: 0 0 3px gray;
cursor: pointer;
}
div#strictIndicator {
width: 6px;
height: 6px;
margin-bottom: 2px;
background-color: #850000;
border-radius: 50%;
border: 1px solid #5f5f5f;
}
#switcher {
display: flex;
justify-content: center;
align-items: center;
}
.labels {
font-family: 'Roboto', sans-serif;
margin: 4px;
}
/* toggle switch */
.checkbox > input[type=checkbox] {
visibility: hidden;
}
.checkbox {
display: inline-block;
position: relative;
width: 60px;
height: 30px;
border: 2px solid #424242;
}
.checkbox > label {
position: absolute;
width: 30px;
height: 26px;
top: 2px;
right: 2px;
background-color: #a50005;
cursor: pointer;
}
.checkbox > input[type=checkbox]:checked + label {
right: 28px;
}
<div id="outerCircle">
<div class="bigButton" id="greenButton" data-sound = "0" >0
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"></audio>
</div>
<div class="bigButton" id="redButton" data-sound = "1">1
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound2.mp3" ></audio>
</div>
<div class="bigButton" id="yellowButton" data-sound = "2">2
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"></audio>
</div>
<div class="bigButton" id="blueButton" data-sound = "3">3
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"></audio>
</div>
<div id="innerCircle">
<div class="additionalBorder">
<p id="tradeMark">simon<span id="reg">®</span></p>
<div class="partition"></div>
<div class="buttons">
<table>
<tr class="firstRow">
<td>
<div class="innerCount"></div>
</td>
<td>
<button type="button" id="innerStart"></button>
</td>
<td>
<div class="strict">
<div id="strictIndicator"></div>
<button type="button" id="strictButton"></button>
</div>
</td>
</tr>
<tr class="labels">
<td>
<div id="countLabel">COUNT</div>
</td>
<td>
<div id="startLabel">START</div>
</td>
<td>
<div id="strictLabel">STRICT</div>
</td>
</tr>
</table>
<div id="switcher">
<span class="labels">ON</span>
<div class="checkbox">
<input id="checkMe" type="checkbox">
<label for="checkMe"></label>
</div>
<span class="labels">OFF</span>
</div>
</div>
</div>
</div>
</div>
<div class="randArray"></div>
One of the problem (along many others) is in checkButton function itself, where you checking buttons against array, but doesn't check the series of button presses, or "attempts".
For example, if randIndexArr contains values [2,2,1,1...], your code is okay with checking clickeBbuttonId with value 2 against both array's first two values, and so on.
I did rewrote only one function checkButton just to show you one of possible approaches:
var currentAttempt = 1
function checkButton(randIndexArr, counter) {
var checker = function checker(e) {
var clickedButtonId = e.target.dataset.sound;
lightenButton(clickedButtonId);
if (randIndexArr[currentAttempt -1] === +(clickedButtonId)){
if (currentAttempt - 1 === counter) {
counter++
currentAttempt = 1
for (var i = 0; i < 4; i++) {
buttonArray[i].removeEventListener("click", checker, false)
}
playGame(randIndexArr, counter);
}
currentAttempt++
} else {
currentAttempt = 1
}
};
for (var i = 0; i < 4; i++) {
buttonArray[i].addEventListener("click", checker, false)
}
}
But to be honest, whole code should be redesigned.

Categories