I am creating a settings portion on a website. I want the features chosen to be "saved" and kept when the page refreshes. I attempted this but it seems to just reset the form when I refresh the page. Another issue is when I click on the cancel button, the toggle buttons reset but the dropdown comes back blank instead of going back to the placeholder "select timezone". The issue most likely lies in my javascript code below. It's also throwing an error in stack overflow but works properly on my website (minus the issues described above). Any suggestions would be much appreciated!
// ---------- TOGGLE BTN ----------
const toggle = document.getElementsByClassName("toggle");
const labels = document.getElementsByClassName("labels");
for(let i=0; i < 2; i++) {
labels[i].innerHTML = "OFF";
toggle[i].addEventListener( "click", () => {
if(labels[i].innerHTML == "OFF") {
// console.log("button toggled");
labels[i].classList.add("on");
labels[i].innerHTML= "ON";
} else {
labels[i].classList.remove("on");
labels[i].innerHTML = "OFF";
}
});
}
// ---------- LOCAL STORAGE DATA ----------
const save = document.getElementById("save");
const cancel = document.getElementById("cancel");
const emailBtn = document.getElementById("togBtn");
const publicBtn = document.getElementById("togBtn2");
const zone = document.getElementById("timezone");
// emailBtn.value = data;
// publicBtn.value = data;
// zone.value = data;
const data = {
email: emailBtn.value,
privacy: publicBtn.value,
timezone: zone.value
}
var emailVal = localStorage.getItem("email");
var privacyVal = localStorage.getItem("privacy");
var zoneVal = localStorage.getItem("timezone");
save.addEventListener('click', () => {
localStorage.setItem("email", emailBtn.value);
localStorage.setItem("privacy", publicBtn.value);
localStorage.setItem("timezone", zone.value);
});
cancel.addEventListener('click', () => {
localStorage.clear();
for(let i=0; i < 2; i++) {
labels[i].innerHTML = "OFF";
labels[i].classList.remove("on");
}
emailBtn.checked = false;
publicBtn.checked =false;
zone.value = 'Select Timezone';
});
.settings {
padding-left: 15px;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
}
.settings h3 {
flex-basis: 100%;
}
.button1,
.button2 {
flex-basis: 100%;
display: flex;
align-items:center;
}
label {
flex-basis: 90%;
}
input {
flex-basis: 10%;
}
.form-field {
flex-basis: 100%;
background-color: rgb(241, 240, 240);
border: 1px solid lightgrey;
color: grey;
border-radius: 5px;
padding: 10px;
margin: 0 15px 10px 0;
}
.settings-button {
display: flex;
justify-content: center;
}
button {
margin: 10px 15px 10px 0;
padding: 10px;
border: 1px solid lightgrey;
border-radius: 5px;
}
#save,
#cancel {
flex-basis: 50%;
}
#save {
background-color: #7477BF;
color: white;
}
#cancel {
background-color: darkgray;
color: white;
}
#timezone {
margin-top:25px;
}
/* toggle button */
.toggle {
-webkit-appearance: none;
-webkit-tap-highlight-color: transparent;
position: relative;
outline: 0;
cursor: pointer;
margin: 10px 15px;
}
.toggle:after {
content: '';
width: 80px;
height: 28px;
display: inline-block;
background: rgba(196, 195, 195, 0.55);
border: 2px solid rgba(196, 195, 195, 0.55);
border-radius: 18px;
clear: both;
}
.toggle:before {
content: '';
width: 20px;
height: 20px;
display: block;
position: absolute;
top: 3px;
/* left: 0;
top: -3px; */
border: 2px solid rgba(196, 195, 195, 0.55);
border-radius: 50%;
background: rgb(255, 255, 255);
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.6);
}
.toggle:checked:before {
left: 54px;
box-shadow: -1px 1px 3px rgba(0, 0, 0, 0.6);
}
.toggle:checked:after {
background: #7477BF;
}
.toggle,
.toggle:before,
.toggle:after,
.toggle:checked:before,
.toggle:checked:after {
transition: ease .4s;
-webkit-transition: ease .4s;
-moz-transition: ease .4s;
-o-transition: ease .4s;
}
.labels {
color: gray;
position: relative;
font-size: 15px;
transform: translate(-48px, -3px);
}
.on {
color: white;
transform: translate(-90px, -3px);
}
<section class="settings" id="settings">
<h3>Settings</h3>
<!-- custom CSS toggle code-->
<div class="button1">
<label for="togBtn">Send Email Notfications </label>
<input type="checkbox" class="toggle" id="togBtn">
<span class="labels"></span>
</div>
<div class="button2">
<label for="togBtn2">Set Profile to Public </label>
<input type="checkbox" class="toggle" id="togBtn2">
<span class="labels"></span>
</div>
<select class="form-field" id="timezone">
<option disabled selected>Select a Timezone</option>
<option>Eastern</option>
<option>Western</option>
<!-- more options -->
</select>
<div class="settings-button" >
<button class="button-primary" id="save">Save</button>
<button class="button-disabled" id="cancel">Cancel</button>
</div>
</section>
here a working example.
The problems with your code were that you were using emailBtn.value and publicBtn.value instead of emailBtn.checked and publicBtn.checked (they are checkbox so in order to get the correct value you have to read che checked property) and you were not loading the saved values on document load (the function inside window.addEventListener("load", ...) in my example.
Hope this helps you.
Related
let myLibrary = [
{
id: 0,
title: "The Once and Future King",
author: "White",
pages: 654,
read: false,
},
{
id: 1,
title: "The Hobbit",
author: "Tolkien",
pages: 304,
read: false,
},
];
const bookContent = document.getElementById("content");
function displayBook(book) {
const addBook = document.createElement("div");
addBook.className = "book";
addBook.id = book.id;
bookContent.appendChild(addBook);
addBook.innerHTML = `
<div class="title">
<p class="bookTitle">
<span>${book.title}</span>
</p>
</div>
<div class="body">
<p>
Author: <span>${book.author}</span>
</p>
<p>
Pages: <span>${book.pages}</span>
</p>
</div>
<div class="read">
<label class="switch" data-book="0">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
<div class="delete">
<button class="delete-btn">DELETE</button>
</div>`;
}
// Display your original object list
myLibrary.forEach((book) => {
displayBook(book);
});
// Handle your object creation
const form = document.getElementById("form");
form.addEventListener("submit", updateLibrary);
function updateLibrary(event) {
// Need this so it doesn't refresh page
event.preventDefault();
const title = document.getElementById("title").value;
const author = document.getElementById("author").value;
const pages = document.getElementById("pages").value;
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
// Adds object to array
myLibrary.push(book);
// Displays new book
displayBook(book);
// Reset form
resetForm();
// Close form
document.getElementById("addBookForm").style.display = "none";
console.log(myLibrary);
}
// Resets the form so user can input another book
function resetForm() {
document.getElementById("form").reset();
}
// The form is automatically set to hidden. This loads it up for the user
const openForm = function () {
document.getElementById("addBookForm").style.display = "block";
document.getElementById("title").focus();
};
// Sets the form display back to none
const closeForm = () =>
(document.getElementById("addBookForm").style.display = "none");
/* .main {
} */
.header {
display: flex;
flex-direction: column;
background-color: #c689c6;
height: 150px;
border: 1px solid #3b133b;
}
.btn {
margin: 0 auto;
margin-top: 55px;
display: block;
text-align: center;
background-color: #4649ff;
padding: 0.75rem 1.25rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
font-size: 1rem;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.btn:hover {
background-color: #3134fa;
}
.content {
display: flex;
flex-flow: row wrap;
align-content: flex-start;
justify-content: flex-start;
background-color: #fffdfa;
height: auto;
}
.book {
border: 2px solid #ffa94d;
background-color: #ffd8a8;
color: #d9480f;
width: 280px;
height: 365px;
margin: 10px;
}
.title {
border-bottom: 2px solid #ffa94d;
}
.title p {
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: larger;
}
.title span {
color: #3c4048;
}
.body {
border: 1px solid transparent;
height: 200px;
background-color: #fff4e6;
}
.body p {
padding-left: 20px;
}
p span {
color: #3c4048;
}
.read {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
border-top: 2px solid #ffa94d;
text-align: center;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .slider {
background-color: #3d8361;
}
input:focus + .slider {
box-shadow: 0 0 1px #3d8361;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.delete {
height: 50px;
border-top: 2px solid #ffa94d;
}
.delete-btn {
margin: 0 auto;
margin-top: 8px;
display: block;
text-align: center;
background-color: #e94560;
padding: 0.5rem 0.75rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.delete-btn:hover {
background-color: #e7082d;
}
.close-btn {
color: #e7082d;
font-size: large;
background-color: #c689c6;
border: none;
float: right;
cursor: pointer;
}
/* THE FORM */
.form-content {
display: flex;
justify-content: center;
}
.form {
display: none;
position: fixed;
margin-top: 5px;
border: 2px solid #3b133b;
animation: openForm 0.5s;
z-index: 1;
}
#keyframes openForm {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
.form h1 {
text-align: center;
}
.form-container {
background-color: #c689c6;
border: 2px solid black;
max-width: 300px;
padding: 10px;
}
.form-container h1 {
padding-left: 20px;
}
.form-container input[type="text"],
.form-container input[type="number"] {
width: 80%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
}
.form-container input[type="text"]:focus,
.form-container input[type="number"]:focus {
outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title>Library</title>
</head>
<body>
<div class="main">
<div class="header">
<button class="btn" id="btn" onclick="openForm()">Add a Book</button>
</div>
<div class="form-content">
<div class="form" id="addBookForm">
<form id="form" action="" class="form-container">
<button type="button" class="close-btn" onclick="closeForm()">
x
</button>
<h1>Add a Book</h1>
<label for="title">Title</label>
<input
type="text"
placeholder="Title"
name="title"
id="title"
required
/>
<label for="author">Author</label>
<input
type="text"
placeholder="Author"
name="author"
id="author"
required
/>
<label for="pages">Pages</label>
<input
type="number"
placeholder="Pages"
name="pages"
required
id="pages"
/>
<button type="submit" id="submit-btn">Submit</button>
</form>
</div>
</div>
<div id="content" class="content"></div>
</div>
</body>
</html>
I have a form where the user inputs information from a book they are reading and upon hitting submit, the information is sent as its own object inside an array. I also have a forEach method running which loops through the array and displays each object as a div on the web page.
let myLibrary = [];
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
myLibrary.push(book)
As you can see from the code above, the three properties that the user fills out are the books title, author and page count. There's also a property that is automatically added called the read property and it is automatically set as false.
The Problem
My problem is this. I have the following code displayed at the bottom of each div.
<div class="read">
<label class="switch">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
This code is very simple. It's a toggle switch which I found here.
I want it so when the toggle switch is grayed out, the read status is set to false. But when the toggle switch is turned on, the read property is set to true. I am having a very difficult time figuring out how to get this done.
What I've Tried
I was able to use an onclick to select the toggle switch's parent element, and I tested it using console.log however I am unsure of where to go from there. I attempted to update the book.read to true using the ternary operator but it was out of scope and resulted in an error.
document.querySelector(".main").onclick = (ev) => {
let el = ev.target.classList.contains("switch")
? ev.target.parentElement
: ev.target.classList.contains("slider")
? ev.target
: false;
if (el) {
let toggle = el.parentElement.parentElement.parentElement;
let index = [...toggle.parentElement.children].indexOf(toggle);
myLibrary[index].read = false ? false : true;
console.log(myLibrary[index].read);
}
console.log(myLibrary);
};
Change this
function displayBook(book) {
...
<label class="switch" data-book="0">
to
function displayBook(book,bookIndex) {
...
<label class="switch" data-book="${bookIndex}">
and
myLibrary.forEach((book) => {
displayBook(book);
});
to
myLibrary.forEach((book,i) => {
displayBook(book,i);
});
lastly change
// Displays new book
displayBook(book);
to
// Displays new book
displayBook(book,myLibrary.length-1);
Here is the code inclusive a delete function
It would be slightly simpler if we had an associate array on book_id
Note I removed the numeric ID because it is not needed since the index of the array is the same
let myLibrary = [{
title: "The Once and Future King",
author: "White",
pages: 654,
read: false,
},
{
title: "The Hobbit",
author: "Tolkien",
pages: 304,
read: false,
},
];
const bookContent = document.getElementById("content");
const formDiv = document.getElementById("addBookForm");
function displayBook(book, idx) {
const addBook = document.createElement("div");
addBook.className = "book";
addBook.id = `book_${idx}`;
bookContent.appendChild(addBook);
addBook.innerHTML = `
<div class="title">
<p class="bookTitle">
<span>${book.title}</span>
</p>
</div>
<div class="body">
<p>
Author: <span>${book.author}</span>
</p>
<p>
Pages: <span>${book.pages}</span>
</p>
</div>
<div class="read">
<label class="switch" data-book="${idx}">
<input type="checkbox" />
<span class="slider round"></span>
</label>
</div>
<div class="delete">
<button class="delete-btn">DELETE</button>
</div>`;
}
// Display your original object list
myLibrary.forEach((book, i) => {
displayBook(book, i);
});
const deleteBook = (e) => {
const parent = e.target.closest("div.book");
const idx = parent.querySelector(".switch").dataset.book;
parent.remove();
console.log(idx);
myLibrary.splice(idx, 1);
console.log(myLibrary);
content.querySelectorAll("div.book").forEach((book, i) => { // reset the hard way
book.id = `book_${i}`;
book.querySelector("label.switch").dataset.book = i;
})
};
content.addEventListener("click", function(e) {
const tgt = e.target;
if (!tgt.matches(".delete-btn")) return; // not the delete
deleteBook(e); // pass the event to the delete
})
// Handle your object creation
const form = document.getElementById("form");
form.addEventListener("submit", updateLibrary);
function updateLibrary(event) {
// Need this so it doesn't refresh page
event.preventDefault();
const title = document.getElementById("title").value;
const author = document.getElementById("author").value;
const pages = document.getElementById("pages").value;
const book = {
title: title,
author: author,
pages: parseInt(pages),
read: false,
};
// Adds object to array
myLibrary.push(book);
// Displays new book
displayBook(book);
// Reset form
resetForm();
// Close form
formDiv.style.display = "none";
console.log(myLibrary);
}
// Resets the form so user can input another book
function resetForm() {
document.getElementById("form").reset();
}
// The form is automatically set to hidden. This loads it up for the user
const openForm = function() {
formDiv.style.display = "block";
document.getElementById("title").focus();
};
// Sets the form display back to none
const closeForm = () => formDiv.style.display = "none";
/* .main {
} */
.header {
display: flex;
flex-direction: column;
background-color: #c689c6;
height: 150px;
border: 1px solid #3b133b;
}
.btn {
margin: 0 auto;
margin-top: 55px;
display: block;
text-align: center;
background-color: #4649ff;
padding: 0.75rem 1.25rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
font-size: 1rem;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.btn:hover {
background-color: #3134fa;
}
.content {
display: flex;
flex-flow: row wrap;
align-content: flex-start;
justify-content: flex-start;
background-color: #fffdfa;
height: auto;
}
.book {
border: 2px solid #ffa94d;
background-color: #ffd8a8;
color: #d9480f;
width: 280px;
height: 365px;
margin: 10px;
}
.title {
border-bottom: 2px solid #ffa94d;
}
.title p {
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: larger;
}
.title span {
color: #3c4048;
}
.body {
border: 1px solid transparent;
height: 200px;
background-color: #fff4e6;
}
.body p {
padding-left: 20px;
}
p span {
color: #3c4048;
}
.read {
display: flex;
align-items: center;
justify-content: center;
height: 50px;
border-top: 2px solid #ffa94d;
text-align: center;
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked+.slider {
background-color: #3d8361;
}
input:focus+.slider {
box-shadow: 0 0 1px #3d8361;
}
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.delete {
height: 50px;
border-top: 2px solid #ffa94d;
}
.delete-btn {
margin: 0 auto;
margin-top: 8px;
display: block;
text-align: center;
background-color: #e94560;
padding: 0.5rem 0.75rem;
border-radius: 10rem;
color: #fff;
cursor: pointer;
letter-spacing: 0.15rem;
transition: all 0.3s;
}
.delete-btn:hover {
background-color: #e7082d;
}
.close-btn {
color: #e7082d;
font-size: large;
background-color: #c689c6;
border: none;
float: right;
cursor: pointer;
}
/* THE FORM */
.form-content {
display: flex;
justify-content: center;
}
.form {
display: none;
position: fixed;
margin-top: 5px;
border: 2px solid #3b133b;
animation: openForm 0.5s;
z-index: 1;
}
#keyframes openForm {
from {
transform: scale(0);
}
to {
transform: scale(1);
}
}
.form h1 {
text-align: center;
}
.form-container {
background-color: #c689c6;
border: 2px solid black;
max-width: 300px;
padding: 10px;
}
.form-container h1 {
padding-left: 20px;
}
.form-container input[type="text"],
.form-container input[type="number"] {
width: 80%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
}
.form-container input[type="text"]:focus,
.form-container input[type="number"]:focus {
outline: none;
}
<div class="main">
<div class="header">
<button class="btn" id="btn" onclick="openForm()">Add a Book</button>
</div>
<div class="form-content">
<div class="form" id="addBookForm">
<form id="form" action="" class="form-container">
<button type="button" class="close-btn" onclick="closeForm()">
x
</button>
<h1>Add a Book</h1>
<label for="title">Title</label>
<input type="text" placeholder="Title" name="title" id="title" required />
<label for="author">Author</label>
<input type="text" placeholder="Author" name="author" id="author" required />
<label for="pages">Pages</label>
<input type="number" placeholder="Pages" name="pages" required id="pages" />
<button type="submit" id="submit-btn">Submit</button>
</form>
</div>
</div>
<div id="content" class="content"></div>
</div>
I'm new to Stack Overflow. I hope that I'm doing this correctly. ❤
I'm working on an old Etch-a-Sketch JavaScript project from months ago and decided to rework the 'mobile' form of the project because I hadn't bothered to do so at the time. At first, I tried just moving the buttons to the top horizontally, but I didn't like any of the variations I tried. So I decided I'd be better off with a dropdown menu instead that would appear when the screen is 500px or smaller, replacing the buttons.
The dropdown menu is supposed to do exactly what the buttons do - when a certain mode is selected, that's the mode that the program is supposed to switch to. For example, when the "Party mode" button is clicked, the program switches to "party mode". I want the dropdown menu to behave similarly - when the "party mode" option is selected, the program should switch to "party mode".
My logic was that I needed a function that grabbed the value of the dropdown menu, and then an "if" condition would run that pretty much says "If the value is x, x mode should run; else if the value is y, y mode should run", and so on. I added the function to the existing window.onload function so it would run upon the window loading. This didn't work.
Note that the dropdown menu will, in the future, only appear when the screen size is 500px or less. In addition, I still have the buttons on the screen for all sizes, just for testing/debugging purposes. When I'm done and have this figured out, the buttons will have "display = 'none'" and be hidden for the "mobile size".
Anyway, so yeah, the program is still just listening to the buttons, and not the dropdown menu. That leads me to believe that I need to somehow turn "off" the button mode? If that's the case, how do I do that? If that's not the case, what am I supposed to do here? Any help or insight would be greatly appreciated. Thanks!
const defaultMode = 'default';
const defaultSize = 30;
const defaultColor = '#0b478b';
let currentMode = defaultMode;
let currentSize = defaultSize;
let currentColor = defaultColor;
// Sets the program's current mode
function setCurrentMode(newMode) {
activeButton(newMode);
currentMode = newMode;
}
// Sets the grid's size
function setCurrentSize(newSize) {
currentSize = newSize;
}
// Sets the color of the square (if in default mode)
function setCurrentColor(newColor) {
currentColor = newColor;
}
// Links the various HTML elements to this script
const sizeValue = document.querySelector('#sizevalue');
const sizeSlider = document.querySelector('#sizeslider');
const colorPicker = document.querySelector('#colorpicker');
const defaultBtn = document.querySelector('#default');
const partyBtn = document.querySelector('#party');
const grayBtn = document.querySelector('#grayscale');
const eraserBtn = document.querySelector('#eraser');
const clearBtn = document.querySelector('#clear');
const grid = document.querySelector('#maincontainer');
// DOM manipulations for buttons, color picker, and size slider
colorPicker.onchange = (e) => setCurrentColor(e.target.value);
defaultBtn.onclick = () => setCurrentMode('default');
partyBtn.onclick = () => setCurrentMode('party');
grayBtn.onclick = () => setCurrentMode('gray');
eraserBtn.onclick = () => setCurrentMode('eraser');
clearBtn.onclick = () => reloadGrid();
sizeSlider.onmousemove = (e) => updateSizeValue(e.target.value);
sizeSlider.onchange = (e) => changeSize(e.target.value);
// When the size is changed, we set the grid size, update the size value (text), and reload the grid.
function changeSize(num) {
setCurrentSize(num);
updateSizeValue(num);
reloadGrid();
}
// When we update the size value, the text changes to reflect the value. (It's a square, so the value is always the same for length and width).
function updateSizeValue(num) {
sizeValue.innerHTML = `${num} x ${num}`;
}
// When we reload the grid (which happens when "Clear grid" is pressed), we ensure that we clear the grid and that the size is still the current size.
function reloadGrid() {
clearGrid()
makeGrid(currentSize)
}
// When we clear the grid, it clears the grid.
function clearGrid() {
grid.innerHTML = ''
}
// Creates the base grid and includes the code that says "when the mouse goes over the squares, draw."
function makeGrid(size) {
grid.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${size}, 1fr)`;
for (i = 0; i < size * size; i++) {
let square = document.createElement('div');
square.addEventListener('mouseover', changeColor);
grid.appendChild(square);
}
}
// These are the conditions to set the color of the "pen" (squares)
function changeColor(e) {
if (currentMode === 'party') {
const randomR = Math.floor(Math.random() * 256);
const randomG = Math.floor(Math.random() * 256);
const randomB = Math.floor(Math.random() * 256);
e.target.style.backgroundColor = `rgb(${randomR}, ${randomG}, ${randomB})`;
} else if (currentMode === 'default') {
e.target.style.backgroundColor = currentColor;
} else if (currentMode === 'gray') {
e.target.style.backgroundColor = calculateGray(e);
} else if (currentMode === 'eraser') {
e.target.style.backgroundColor = 'white';
}
}
// Shading mode code
function calculateGray(e) {
let clr = returnRGB(e.target.style.backgroundColor);
if (!clr || clr[1] !== clr[2] || clr[1] !== clr[3]) {
return `rgb(255, 255, 255)`;
}
return clr[1] <= 0 ? `rgb(255, 255, 255)` : `rgb(${clr[1]-25}, ${clr[1]-25}, ${clr[1]-25})`;
}
function returnRGB(num) {
return num.match(/rgb\(([0-9]*), ([0-9]*), ([0-9]*)\)/);
}
// Changes the button styling to indicate which mode is the active mode
function activeButton(newMode) {
if (currentMode === 'party') {
partyBtn.classList.remove('active');
} else if (currentMode === 'default') {
defaultBtn.classList.remove('active');
} else if (currentMode === 'gray') {
grayBtn.classList.remove('active');
} else if (currentMode === 'eraser') {
eraserBtn.classList.remove('active');
}
if (newMode === 'party') {
partyBtn.classList.add('active');
} else if (newMode === 'default') {
defaultBtn.classList.add('active');
} else if (newMode === 'gray') {
grayBtn.classList.add('active');
} else if (newMode === 'eraser') {
eraserBtn.classList.add('active');
}
}
// Ensures that, when we load the page, we make the grid and activate the correct mode (default).
window.onload = () => {
makeGrid(defaultSize);
activeButton(defaultMode);
dropdownModeThing(document.getElementById('dropdown-mode').value);
}
// Code for the dropdown menu
function dropdownModeThing(val) {
if (val === 'default') {
setCurrentMode('default');
} else if (val === 'party') {
setCurrentMode('party');
} else if (val === 'shading') {
setCurrentMode('gray');
} else if (val === 'eraser') {
setCurrentMode('eraser');
} else if (val === 'clear') {
reloadGrid();
}
}
body,
html {
min-height: 100vh;
height: 100%;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: 0;
padding: 0;
background-color: white;
overflow-x: hidden;
}
header {
text-align: center;
margin: 0;
border-bottom: 1px solid black;
background-color: #0b478b;
color: white;
padding: 10px;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
p {
margin: 0;
}
h1 {
text-align: center;
margin: 0;
font-size: 2.5rem;
padding: 0;
}
#maincontainer {
background-color: white;
margin: 20px auto 10px auto;
display: grid;
border: 1px solid black;
width: 45vw;
height: 45vw;
min-height: 300px;
min-width: 300px;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
.testing {
padding-top: 100%;
color: hsla(0, 0%, 68%, 0.596);
}
#btncontainer {
padding-top: 20px;
display: flex;
flex-direction: column;
justify-content: flex-start;
}
a {
color: #2aa5a1;
text-decoration: none;
}
a:hover {
color: white;
}
button {
background-color: #2aa5a1;
color: white;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
border: 1px solid black;
margin: 10px 15px;
padding: 8px 10px;
font-size: .9em;
transition: 0.3s;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
button:active {
background-color: #3F86D8;
color: white;
border: 1px solid black;
}
.active {
background-color: #3F86D8;
transition: 0.3s;
color: white;
border: 1px solid black;
}
button:hover {
background-color: #0b478b;
color: white;
border: 1px solid black;
opacity: 1;
}
#rightside {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
text-align: center;
min-height: 500px;
padding: 0;
margin: 0;
}
#sizevalue {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin-bottom: 0;
}
input[type=range] {
background-color: white;
height: 28px;
-webkit-appearance: none;
margin: 0;
margin-bottom: 35px;
width: 250px;
padding: 0;
}
input[type=range]:focus {}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000;
background: #3F86D8;
border-radius: 13px;
border: 0px solid #010101;
}
input[type=range]::-webkit-slider-thumb {
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #FFFFFF;
cursor: pointer;
-webkit-appearance: none;
margin-top: -5px;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #3F86D8;
}
input[type=range]::-moz-range-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
box-shadow: 1px 1px 1px #000000;
background: #3F86D8;
border-radius: 13px;
border: 0px solid #010101;
}
input[type=range]::-moz-range-thumb {
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #F3EEED;
cursor: pointer;
}
input[type=range]::-ms-track {
width: 100%;
height: 11px;
cursor: pointer;
animate: 0.2s;
background: transparent;
border-color: transparent;
color: transparent;
}
input[type=range]::-ms-fill-lower {
background: #3F86D8;
border: 0px solid #010101;
border-radius: 26px;
box-shadow: 1px 1px 1px #000000;
}
input[type=range]::-ms-fill-upper {
background: #3F86D8;
border: 0px solid #010101;
border-radius: 26px;
box-shadow: 1px 1px 1px #000000;
}
input[type=range]::-ms-thumb {
margin-top: 1px;
box-shadow: 1px 1px 2px #000031;
border: 1px solid #00001E;
height: 20px;
width: 20px;
border-radius: 15px;
background: #F3EEED;
cursor: pointer;
}
input[type=range]:focus::-ms-fill-lower {
background: #3F86D8;
}
input[type=range]:focus::-ms-fill-upper {
background: #3F86D8;
}
main {
display: flex;
justify-content: center;
margin: 0;
margin-bottom: 20px;
padding: 0;
}
#colorpicker {
-webkit-appearance: none;
border-radius: 100vw;
width: 50px;
height: 50px;
padding: 0;
margin: 0 auto 10px auto;
overflow: hidden;
border: 1px solid black;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
input[type='color']:hover {
transform: scale(1.05);
}
input[type='color']::-webkit-color-swatch-wrapper {
padding: 0;
}
input[type='color']::-webkit-color-swatch {
border: none;
border-radius: 50px;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
/* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
top: 50%;
right: 100%;
/* To the left of the tooltip */
margin-top: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent black transparent transparent;
}
footer {
color: white;
text-align: center;
background-color: #0b478b;
position: fixed;
bottom: 0;
width: 100%;
margin: 0;
padding-top: 10px;
padding-bottom: 15px;
}
#media (max-width: 500px) {
main {
flex-direction: column;
}
#btncontainer {
margin: 0 auto;
padding: 20px 10px 5px 10px;
flex-wrap: wrap;
flex-direction: row;
justify-content: center;
}
#btncontainer button {
margin: 0 3px;
height: 35px;
}
#colorpicker {
-webkit-appearance: none;
border-radius: 100px;
width: 35px;
height: 35px;
padding: 0;
margin: 0 auto 10px auto;
overflow: hidden;
border: 1px solid black;
box-shadow: rgba(0, 0, 0, 0.15) 0px 3px 3px 0px;
}
}
<!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">
<!-- CSS spreadsheet -->
<link href="styles.css" rel="stylesheet">
<title>Etch-a-Sketch</title>
</head>
<body>
<!-- Note that this is set up in various divs so
that we can use Flex to create our wanted layout. -->
<div id="entirepage">
<header>
<h1>Etch-a-Sketch</h1>
<p title="Testing">Select a color or a different mode, then select your size, and get drawing!</p>
</header>
<main>
<div id="btncontainer">
<select id="dropdown-mode">
<option value="default">Default mode</option>
<option value="party">Party mode</option>
<option value="shading">Shading</option>
<option value="eraser">Eraser mode</option>
<option value="clear">Clear grid</option>
</select>
<input type="color" id="colorpicker" value="#0b478b">
<button id="default">Default mode</button>
<button id="party">Party mode</button>
<button id="grayscale">Shading</button>
<button id="eraser">Eraser mode</button>
<button id="clear">Clear grid</button>
</div>
<div id="rightside">
<div id="maincontainer">
</div>
<label for="sizeslider" id="sizevalue">30 x 30</label>
<input type="range" min="1" max="100" value="30" id="sizeslider">
</div>
</main>
<footer>
<p>Created by Sara Dunlop (RiscloverYT)</p>
</footer>
</div>
<!-- JavaScript script -->
<script src="script.js"></script>
</body>
</html>
Luckily, there's an easy way to do that. Add this piece of code into your javascript file and see the magic.
const dropdown = document.getElementById('dropdown-mode');
dropdown.addEventListener('change', (e) => {
setCurrentMode(e.target.value);
});
Read more about change event here.
So when I click my start button, this function is working and I can see it
const displayFirstQuestion = () => {
main.insertAdjacentHTML("afterbegin",
`<div class="question-container">
<h2 class="question-tag">QUESTION 1</h2>
<h3 class="question">
What is the keyword to define a variable that can be modified?
</h3>
<div class="choices">
<p class="choice">A. Function</p>
<p class="choice">B. Const</p>
<p class="choice correct">C. Let</p>
<p class="choice">D. Var</p>
</div>
Next Question >>
</div>` );
};
So I want to select the element with 'correct' classname but it doesn't work. When I print it to the console, it says 'null' basically.
document.querySelector('.correct') // this is null
I tried to put the selector after inserting Html and other different places. It always says null.
Here is the codepen link:
https://codepen.io/raskolnikovcykakekw/pen/mdrvVqX
I just tried you code on browser console and it worked. I just had to close the template string in the 2nd arg of insertAdjacentHTML. Can you provide more info?
Update
Ok, I see. The problem is you are querying and registering events on elements when they aren't in the DOM yet. So, I'd suggest to:
Wrap the loop for registering .choice event listeners in a function and call it right after call displayFirstQuestion;
Query .correct and .nextButton inside answering function.
Something like this:
"use strict";
const main = document.querySelector(".main");
const container = document.querySelector(".container");
const startButton = document.querySelector(".start-button");
const questionContainer = document.querySelector(".question-container");
const choice = [...document.querySelectorAll(".choice")];
const correct = document.querySelector(".correct");
const nextButton = document.querySelector(".next-button");
const endingContanier = document.querySelector(".ending");
////////////////----------------------//////////////---------SELECTING QUESTIONS ---------//////
const displayFirstQuestion = () => {
main.insertAdjacentHTML(
"afterbegin",
`<div class="question-container">
<h2 class="question-tag">QUESTION 1</h2>
<h3 class="question">
What is the keyword to define a variable that can be modified?
</h3>
<div class="choices">
<p class="choice">A. Function</p>
<p class="choice">B. Const</p>
<p class="choice correct">C. Let</p>
<p class="choice">D. Var</p>
</div>
Next Question >>
</div>`
);
};
startButton.addEventListener("click", () => {
container.style.animation = "hidden 1s forwards";
setTimeout(() => {
container.remove();
}, 500);
setTimeout(displayFirstQuestion(), 501);
setTimeout(registerEventListeners(), 600);
});
//////////////////////////////////
const answering = function (element) {
const correct = document.querySelector(".correct");
if (!element.target.classList.contains("correct")) {
element.target.style.background = "red";
correct.style.background = "green";
} else {
correct.style.background = "green";
}
setTimeout(() => {
const nextButton = document.querySelector(".next-button");
nextButton.style.animation = "come-out 0.5s ease";
nextButton.style.display = "inline";
}, 300);
choice.forEach((e) => e.removeEventListener("click", answering));
};
const registerEventListeners = function() {
const choice = document.querySelectorAll(".choice");
choice.forEach(function (e) {
e.addEventListener("click", answering);
});
console.log(correct);
}
* {
margin: 0;
box-sizing: border-box;
}
body {
font-family: "Source Code Pro", monospace;
background: rgba(0, 0, 0, 0.685);
}
a {
text-decoration: none;
color: white;
}
h2 {
background: #323330;
padding: 0.5rem;
border: 1px solid #323330;
border-radius: 10px;
margin-bottom: 30px;
}
.container {
color: white;
display: flex;
flex-direction: column;
align-items: center;
margin: 15rem 0 0 0;
animation: come-out 1s forwards;
}
.start-button {
font-family: "Source Code Pro", monospace;
font-weight: 700;
width: 250px;
height: 55px;
font-size: 1.6rem;
color: #323330;
background: rgb(240, 219, 79);
margin: 2rem;
cursor: pointer;
border-bottom: 5px solid rgb(211, 191, 59);
border-left: 5px solid rgb(211, 191, 59);
border-right: 5px solid rgb(211, 191, 59);
border-top: 1px solid rgb(211, 191, 59);
transition: all 0.3s ease;
border-radius: 10px;
}
.start-button:hover {
color: rgb(240, 219, 79);
background: #323330;
border: 5px solid #323330;
}
.start-button:active {
transform: translate(5%);
}
.question-container {
color: white;
display: flex;
flex-direction: column;
align-items: center;
margin: 5rem 0 0 0;
line-height: 3rem;
font-size: 1.1rem;
animation: come-out 1s forwards;
}
.question {
margin: 0 0 3% 0;
text-align: center;
}
.choices {
flex-direction: column;
}
.choice {
cursor: pointer;
padding: 0 10px 0 10px;
margin-bottom: 10%;
background: rgba(0, 0, 0, 0.432);
border: 1px solid black;
border-radius: 12px;
box-shadow: 1px 1px 6px black;
transition: all 0.5s ease;
text-align: center;
}
.choice:hover {
background: rgba(0, 0, 0, 0.232);
}
.choice:active {
background: rgba(240, 218, 79, 0.229);
transform: translate(5%);
}
.choice-align-left {
text-align: left;
}
.next-button {
position: absolute;
top: 65%;
font-size: 20px;
height: 8vh;
font-family: "Source Code Pro", monospace;
color: white;
cursor: pointer;
margin-right: 15%;
background: rgba(0, 0, 0, 0.432);
border: 1px solid black;
border-radius: 5px;
box-shadow: 1px 1px 6px black;
align-self: flex-end;
display: none;
transition: all 0.5s ease;
}
.next-button:hover {
background: rgba(0, 0, 0, 0.232);
}
.next-button:active {
transform: translate(5%);
}
.back-button {
height: 3rem;
width: 20rem;
}
#keyframes hidden {
0% {
opacity: 1;
}
100% {
display: none;
opacity: 0;
}
}
#keyframes come-out {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.q2-green {
color: rgba(86, 221, 86, 0.596);
}
.q2-yellow {
color: yellow;
}
<body>
<main class="main">
<div class="container">
<h1>
WELCOME TO
<img src="logo.png" alt="js-logo" width="50px" height="50px" /> QUIZ
</h1>
<button class="start-button">LET'S START</button>
</div>
</main>
<script src="script.js"></script>
</body>
Then you can clean up a bit some code.
I have been trying to figure out how to get an index of a dynamically created element so that I can write a function to delete it (splice).
I have figured out how to get the index really manually, but the problem is that I am getting Propagation from my event delegation and I am not sure how to stop it.
I have tried putting stopPropagation(), preventDefault(), stopImmediatePropagation() at various points within the function and have spent the last hour reading around online trying to figure out how to stop it. I even tried setting the e.bubble to false with no avail.
Could someone point me in the right direction here? Im sure its my inexperience but I am just out of ideas as of now.
// Title of Question Set
const title = document.querySelector(".input_title-input");
// Array of Questions
const questions = [];
let chosen = [];
// Selected Question
let qChosen = [];
// Toggles if a new question is selected
let toggle = 0;
// Selecting Inputs and Button
let question = document.querySelector(".input_question-input");
let answer = document.querySelector(".input_answer-input");
let submit = document.querySelector(".input_submit-button");
let display = document.querySelector(".input_display");
let card = document.querySelector(".card_container");
let start = document.querySelector(".input_start-btn");
let guessInput = document.querySelector(".guess_input");
let submitGuess = document.querySelector(".submitGuess");
let nextQuestion = document.querySelector(".nextQuestion");
// Select all display items
let displayItems = document.getElementsByClassName("input_display-item");
// Select P quiz card values
let cardQuestion = document.querySelector(".quiz_question");
let cardAnswer = document.querySelector(".quiz_answer");
// Event Listener on Submit Button for Display Items Idividually
submit.addEventListener("click", function() {
if (question.value === "") {
question.classList.toggle("error");
answer.classList.toggle("error");
} else {
createObj();
let trashCan = createDisplayItem();
trashCan.addEventListener("click", function(e) {
console.log(this.parentNode);
console.log(questions);
console.log(e);
this.parentNode.remove();
});
inputReset();
toggle = questions.length;
start.removeAttribute("disabled");
}
});
start.addEventListener("click", function() {
console.log("clicked");
generateCard();
});
// Event Listener to test if guess is correct
submitGuess.addEventListener("click", function() {
if (guessInput.value.toLowerCase() === qChosen.answer.toLowerCase()) {
card.classList.toggle("flip");
submitGuess.disabled = true;
} else {
console.log("wrong or not working");
}
});
nextQuestion.addEventListener("click", function() {
card.classList.toggle("flip");
submitGuess.disabled = false;
setTimeout(generateCard, 1000);
});
// Create The object for inclusion to array
function createObj() {
let obj = {};
obj.question = question.value;
obj.answer = answer.value;
questions.push(obj);
}
// Resets inputs to blank after submit
function inputReset() {
question.value = "";
answer.value = "";
if (question.classList.contains("error")) {
question.classList.toggle("error");
answer.classList.toggle("error");
}
}
// Creates Each Display Item
function createDisplayItem() {
// Create new Div
let newUl = document.createElement("ul");
// Create Li and Image Elements
let liQuestion = document.createElement("li");
let liAnswer = document.createElement("li");
let trashCan = document.createElement("img");
// Set img src
trashCan.src = "../assets/trash.svg";
// Set classes
newUl.className = "input_display-item";
liQuestion.className = "input_display-question";
liAnswer.className = "input_display-answer";
trashCan.className = "input_display-delete";
// Set LI textContent
liQuestion.textContent = question.value;
liAnswer.textContent = answer.value;
// Append Children
display.appendChild(newUl);
newUl.appendChild(liQuestion);
newUl.appendChild(liAnswer);
return newUl.appendChild(trashCan);
}
//Generating Card Information per question
function generateCard() {
random();
if (toggle < 0) {
cardQuestion.textContent = "There are no more questions left";
cardAnswer.textContent = "There are no more questions left";
} else {
cardQuestion.textContent = qChosen.question;
cardAnswer.textContent = qChosen.answer;
}
}
// Choses a random value for the selection set
function random() {
if (questions.length === 0) {
toggle = -1;
} else {
let num = Math.floor(Math.random() * questions.length);
chosen = questions.splice(num, 1).concat(chosen);
qChosen = chosen[0];
}
}
// Notes
// I need to create a function that upon submit of a guess, checks its value against the answer textContent.
// I will likely need to make the text lowercase for the check to just make sure that they match exactly and that a capital letter wont create a false when its true.
/** Variables
---------------------------------------------------------*/
/** Reset
---------------------------------------------------------*/
* {
margin: 0;
padding: 0; }
*,
*::before,
*::after {
box-sizing: inherit; }
html {
box-sizing: border-box;
font-size: 62.5%; }
body {
font-weight: 400;
line-height: 1.5;
font-size: 2rem;
background-color: #bdbdc7; }
/** Primary Container
---------------------------------------------------------*/
.container {
max-width: 180rem;
display: flex; }
.flex {
display: flex;
justify-content: center;
align-items: center; }
.visible {
visibility: hidden; }
/** Input Section
---------------------------------------------------------*/
input[type="text"] {
padding: 0.5rem;
width: auto;
min-width: 100%;
line-height: 2rem; }
.input {
width: 40rem;
height: 100%;
padding: 1rem;
background-color: #ccc;
display: flex;
align-items: flex-start;
flex-direction: column; }
.input_title {
width: 100%;
display: flex;
flex-direction: column; }
.input_title-label {
display: flex;
justify-content: center; }
.input_title-input {
padding: 0.5rem; }
.input_question {
width: 100%;
display: flex;
flex-direction: column; }
.input_question-label {
display: flex;
justify-content: center; }
.input_question-input {
padding: 0.5rem; }
.input_answer {
width: 100%;
display: flex;
flex-direction: column; }
.input_answer-label {
display: flex;
justify-content: center; }
.input_answer-input {
padding: 0.5rem; }
.input_question-input.error, .input_answer-input.error {
border: 2px red solid; }
.input_submit {
width: 100%; }
.input_submit-button {
margin-top: 1rem;
padding: 0 1.5rem; }
.input_start {
width: 100%; }
.input_display {
width: 100%;
font-size: 1.5rem;
padding: 2rem 0 1rem 0; }
.input_display-item {
margin-bottom: 1rem;
padding: .2rem 2rem;
text-transform: capitalize;
background-color: #fff;
border-radius: 1rem;
list-style: none;
display: flex;
justify-content: space-between;
align-items: center; }
.input_display-item:nth-child(odd) {
background-color: #aaa;
border-radius: 1rem; }
.input_display-delete {
height: 1.8rem;
width: 1.8rem; }
.input :not(.input_display) div {
padding-bottom: 2rem; }
/** Quiz Card
---------------------------------------------------------*/
.card {
display: flex;
justify-content: center;
align-items: center;
width: 100%; }
.card_container {
transform-style: preserve-3d;
perspective: 1000px;
width: 60rem;
margin: 1rem;
cursor: pointer; }
.card_container .front {
transform: rotateY(0deg);
transform-style: preserve-3d; }
.card_container .front:after {
position: absolute;
top: 0;
left: 0;
z-index: 1;
width: 100%;
height: 100%;
content: "";
display: block;
opacity: 0.6;
background-color: #000;
backface-visibility: hidden;
border-radius: 10px; }
.card_container .back {
position: absolute;
top: 0;
left: 0;
width: 100%;
background-color: #cedce7;
background: linear-gradient(45deg, #dedce7 0%, #596a72 100%);
transform: rotateY(180deg);
transform-style: preserve-3d; }
.card_container .front,
.card_container .back {
background-color: red;
background-size: cover;
background-position: center;
transition: transform 0.7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: transform 0.7s cubic-bezier(0.4, 0.2, 0.2, 1);
backface-visibility: hidden;
text-align: center;
min-height: 500px;
height: auto;
border-radius: 10px;
color: #fff;
font-size: 1.5rem; }
.flip {
transition: transform 0.7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: transform 0.7s cubic-bezier(0.4, 0.2, 0.2, 1); }
.flip .back {
transform: rotateY(0deg);
transform-style: preserve-3d; }
.flip .front {
transform: rotateY(-180deg);
transform-style: preserve-3d; }
.inner {
transform: translateY(-50%) translateZ(60px) scale(0.94);
top: 50%;
position: absolute;
left: 0;
width: 100%;
padding: 2rem;
box-sizing: border-box;
outline: 1px solid transparent;
perspective: inherit;
z-index: 2; }
.front .inner p {
font-size: 2rem;
margin-bottom: 2rem;
position: relative; }
.card_container-guess {
padding-top: 2rem; }
.card_container-guess .guess_input {
width: 2rem;
margin: 1rem auto;
padding: 1rem;
border-radius: 1rem;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.55), 0px 1px 1px rgba(255, 255, 255, 0.5);
border: 1px solid #666;
opacity: 0.6; }
.card_container-guess .guess_input:hover, .card_container-guess .guess_input:focus {
opacity: .8;
color: #08c;
box-shadow: 0px 1px 0px rgba(255, 255, 255, 0.25), inset 0px 3px 6px rgba(0, 0, 0, 0.25); }
.btnNew {
height: 5rem;
width: 12rem;
margin: 1.5rem 3rem 1rem 0;
font-weight: 700;
color: #333;
background-image: linear-gradient(top, #f4f1ee, #fff);
box-shadow: 0px 8px 30px 1px rgba(0, 0, 0, 0.3), inset 0px 4px 1px 1px white, inset 0px -3px 1px 1px rgba(204, 198, 197, 0.5);
border-radius: 5%;
position: relative;
transition: all .1s linear;
outline: none; }
.btnNew:after {
color: #e9e6e4;
content: "";
display: block;
font-size: 30px;
height: 3rem;
text-decoration: none;
text-shadow: 0px -1px 1px #bdb5b4, 1px 1px 1px white;
position: absolute;
width: 3rem; }
.btnNew:hover {
background-image: linear-gradient(top, #fff, #f4f1ee);
color: #0088cc; }
.btnNew:active {
background-image: linear-gradient(top, #efedec, #f7f4f4);
box-shadow: 0 3px 5px 0 rgba(0, 0, 0, 0.4), inset opx -3px 1px 1px rgba(204, 198, 197, 0.5);
outline: none; }
.btnNew:active:after {
color: #dbd2d2;
text-shadow: 0px -1px 1px #bdb5b4, 0px 1px 1px white;
outline: none; }
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Flash</title>
<!-- Custom CSS -->
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<section class="input">
<div class="input_title">
<label class="input_title-label" for="title">Enter a Title</label>
<input class="input_title-input" id="title" type="text" placeholder="List of Towels">
</div>
<div class="input_question">
<label class="input_question-label" for="question">Enter a Question</label>
<input class="input_question-input" id="question" type="text" placeholder="What is 42?">
</div>
<div class="input_answer">
<label class="input_answer-label" for="answer">Enter an Answer</label>
<input class="input_answer-input" id="answer" type="text" placeholder="The Meaning Life, Universe, and Everything">
</div>
<div class="input_submit flex">
<button class="input_submit-button btnNew">Submit</button>
</div>
<div class="input_display"></div>
<div class="input_start flex">
<button type="button" class="input_start-btn btnNew" disabled>Start Quiz</button>
</div>
</section>
<section class="card">
<div class="card_container">
<div class="front">
<div class="inner">
<p class="quiz_question">Question</p>
</div>
</div>
<div class="back">
<div class="inner">
<p class="quiz_answer">Answer</p>
</div>
</div>
<div class="card_container-guess">
<input type="text" class="guess_input">
<button class="submitGuess btnNew">Submit Guess</button>
<button class="nextQuestion btnNew">Next Question</button>
</div>
</div>
</section>
</div>
<!-- Custom JS -->
<script src="js/scripts.js"></script>
</body>
</html>
I am wanting to figure out how to delete an item from the list
How about we change the last line of the function createDisplayItem to ..
function createDisplayItem(){
...
return newUl.appendChild(trashCan) // Added return
}
Now, you have an instance of the newly created trash can element being returned to the calling code, so now all we have to do is add a click event to this specific trash can element and let it delete its parent ul ..
submit.addEventListener("click", function() {
...
let trashCan = createDisplayItem();
trashCan.addEventListener('click', function(){
confirm('Are you sure you want to delete this?')
&& this.parentNode.remove()
})
...
});
So, since now in this code, each trash can takes care of its own parent element, you do not have to worry about finding the index from the parent display element anymore.
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).