Related
I am working on the etch-a-sketch project with The Odin Project and there's one thing I can't figure out. In the original project the grid elements will start to change colors once I hover over them but what I want to do is to only start the hovering function after I press the left mouse button.
Here is a working example of what I want to achieve.
const container = document.getElementById('container');
const reset = document.getElementById('reset');
const eraser = document.querySelector('#eraser');
const pencil = document.querySelector('#pencil');
const rainbow = document.querySelector('#rainbow');
const pickColor = document.querySelector('#color');
const shading = document.querySelector('#shading')
const gridSize = document.querySelector('#range');
let gridValue = document.querySelector('.grid-size');
let mode = '';
gridValue.textContent = `50x50`; // display default size of the grid
// create grid
function createGrid(size) {
size = gridSize.value;
container.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
container.style.gridTemplateRows = `repeat(${size}, 1fr)`;
for (let i = 0; i < size * size; i++) {
const grid = document.createElement('div');
grid.setAttribute('id', 'grid');
container.appendChild(grid);
grid.addEventListener('mouseover', changeColor);
}
}
createGrid();
// change grid size depending on the user's choice
gridSize.addEventListener('input', function (e) {
let currentSize = e.target.value;
gridValue.textContent = `${currentSize}x${currentSize}`;
resetGrid();
});
// change color
function changeColor(e) {
if (mode === 'pencil') {
e.target.classList.add('black');
e.target.classList.remove('white');
e.target.style.backgroundColor = null;
e.target.style.opacity = null;
} else if (mode === 'rainbow') {
const green = Math.floor(Math.random() * 250);
const blue = Math.floor(Math.random() * 250);
const red = Math.floor(Math.random() * 250);
e.target.style.backgroundColor = `rgb(${red}, ${green}, ${blue})`;
e.target.style.opacity = null;
} else if (mode === 'erase') {
e.target.classList.add('white');
e.target.style.backgroundColor = null;
e.target.style.opacity = null;
} else if (mode === 'pickColor') {
e.target.style.backgroundColor = pickColor.value;
e.target.style.opacity = null;
} else if (mode === 'shading') {
e.target.classList.remove('white');
e.target.classList.add('black');
e.target.style.opacity = Number(e.target.style.opacity) + 0.2;
} else {
e.target.classList.add('black')
}
}
// reset grid
reset.addEventListener('click', () => resetGrid());
function resetGrid() {
container.innerHTML = '';
createGrid();
}
// erase
eraser.addEventListener('click', () => eraseMode());
function eraseMode() {
mode = 'erase';
}
// pencil
pencil.addEventListener('click', () => pencilMode());
function pencilMode() {
mode = 'pencil';
}
// rainbow
rainbow.addEventListener('click', () => rainbowMode());
function rainbowMode() {
mode = 'rainbow';
}
// pick a color
pickColor.addEventListener('click', () => pickColorMode());
function pickColorMode() {
mode = 'pickColor';
}
// shading
shading.addEventListener('click', () => shadeMode());
function shadeMode() {
mode = 'shading';
}
#import url('https://fonts.googleapis.com/css2?family=Inconsolata:wght#700;800&display=swap');
body {
text-align: center;
background-color: #4d56bd;
font-family: 'Inconsolata', monospace;
color: white;
}
h1 {
font-weight: 800;
font-size: 40px;
text-shadow: 3px 3px #1d1b1e;
color: #f4ce45
}
#container {
width: 600px;
height: 600px;
border: 3px solid #1d1b1e;
display: grid;
margin: 20px auto;
background-color: white;
box-shadow: 5px 5px #303030;
}
#grid {
border: none;
}
.black {
background-color: black;
}
.white {
background-color: white;
}
.button {
font-family: inherit;
padding: 10px;
font-size: 1em;
background-color: #303030;
box-shadow: 2px 2px #1d1b1e;
color: white;
margin: 0 5px;
}
#reset {
background-color: #f4ce45;
color: black;
}
.button:hover,
#reset:hover {
cursor: pointer;
background-color: #e7455a;
}
.ownColor {
margin: 10px;
}
.pickColor:hover {
cursor: auto;
background-color: #303030;
}
#color {
cursor: pointer;
}
.slider {
-webkit-appearance: none;
width: 30%;
height: 10px;
border-radius: 5px;
background: #1d1b1e;
margin: 10px;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: #f4ce45;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: #f4ce45;
cursor: pointer;
}
.grid-size {
font-size: 1.5rem;
margin-top: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<title>Etch-a-Sketch</title>
</head>
<body>
<h1>ETCH A SKETCH</h1>
<button id="reset" class="button">Reset</button>
<button id="pencil" class="button">Pencil</button>
<button id="eraser" class="button">Eraser</button>
<button id="rainbow" class="button">Rainbow</button>
<button id="shading" class="button">Shading</button>
<div class="ownColor">
<button class="button pickColor">Choose your own color:
<input type="color" id="color"></button>
</div>
<div class="grid-size"></div>
<input type="range" id="range" min="5" max="100" class="slider">
<div id="container"></div>
</body>
<script src="script.js"></script>
</html>
Well basically you can achieve this with a variable isMouseDown.
let isMouseDown;
document.addEventListener('mousedown', () => isMouseDown = true);
document.addEventListener('mouseup', () => isMouseDown = false);
then, use it where you need, for example:
// change color
function changeColor(e) {
if(!isMouseDown) return;
// ... rest of the code
}
I'm looking for advice/tips on how to fix a function that is supposed to remove items from localStorage. I'm following a tutorial by John Smilga that I found on Youtube. Although I've modeled my code on his, apparently, I have missed something.
This function works perfectly well if I run it manually from the console and pass in the id of the item that I want to remove from localStorage.
function removeFromLocalStorage(id) {
console.log(id);
let storageItems = getLocalStorage();
console.log(storageItems);
storageItems = storageItems.filter(function(singleItem) {
if (singleItem.id !== id) {
return singleItem;
}
})
console.log(storageItems);
localStorage.setItem("list", JSON.stringify(storageItems));
}
However, when this function is triggered by the deleteItem() function, it refuses to remove the item from localStorage. It still works, there are a bunch of console.logs in it that track its execution, and I can check that it receives the correct item id as the argument, but for some reason it doesn't filter out the item that needs to be removed. I am completely lost and have no idea how to identify the problem. I can't debug it with console.logs as I usually do. I will be very grateful if you help me find the problem. Any advice will be appreciated.
In case the entire code is needed, please find it below.
const form = document.querySelector(".app__form");
const alert = document.querySelector(".app__alert");
const input = document.querySelector(".app__input");
const submitBtn = document.querySelector(".app__submit-btn");
const itemsContainer = document.querySelector(".app__items-container");
const itemsList = document.querySelector(".app__items-list");
const clearBtn = document.querySelector(".app__clear-btn");
let editElement;
let editFlag = false;
let editId = "";
form.addEventListener("submit", addItem);
clearBtn.addEventListener("click", clearItems);
function addItem(e) {
e.preventDefault();
const id = Math.floor(Math.random() * 9999999999);
if (input.value && !editFlag) {
const item = document.createElement("div");
item.classList.add("app__item");
const attr = document.createAttribute("data-id");
attr.value = id;
item.setAttributeNode(attr);
item.innerHTML = `<p class='app__item-text'>${input.value}</p>
<div class='app__item-btn-cont'>
<button class='app__item-btn app__item-btn--edit'>edit</button>
<button class='app__item-btn app__item-btn--delete'>delete</button>
</div>`
const editBtn = item.querySelector(".app__item-btn--edit");
const deleteBtn = item.querySelector(".app__item-btn--delete");
editBtn.addEventListener("click", editItem);
deleteBtn.addEventListener("click", deleteItem);
itemsList.appendChild(item);
displayAlert("item added", "success");
addToLocalStorage(id, input.value);
setBackToDefault();
itemsContainer.classList.add("app__items-container--visible");
} else if (input.value && editFlag) {
editElement.textContent = input.value;
// edit local storage
editLocalStorage(editId, input.value);
setBackToDefault();
displayAlert("item edited", "success");
} else {
displayAlert("empty field", "warning");
}
}
function setBackToDefault() {
input.value = "";
editFlag = false;
editId = "";
submitBtn.textContent = "Submit";
submitBtn.className = "app__submit-btn";
}
function displayAlert(text, action) {
alert.textContent = text;
alert.classList.add(`app__alert--${action}`);
setTimeout(function() {
alert.textContent = "";
alert.classList.remove(`app__alert--${action}`);
}, 700)
}
function clearItems() {
const items = document.querySelectorAll(".app__item");
if (items.length > 0) {
items.forEach(function(singleItem) {
itemsList.removeChild(singleItem);
})
itemsContainer.classList.remove("app__items-container--visible");
displayAlert("items cleared", "cleared");
setBackToDefault();
}
}
function editItem(e) {
const item = e.currentTarget.parentElement.parentElement;
editElement = e.currentTarget.parentElement.previousElementSibling;
editId = item.dataset.id;
editFlag = true;
input.value = editElement.textContent;
submitBtn.textContent = "Edit";
submitBtn.classList.add("app__submit-btn--edit");
input.focus();
}
function deleteItem(e) {
const item = e.currentTarget.parentElement.parentElement;
const itemId = item.dataset.id;
removeFromLocalStorage(itemId);
displayAlert("item removed", "cleared");
setBackToDefault();
itemsList.removeChild(item);
if (itemsList.children.length === 0) {
itemsContainer.classList.remove("app__items-container--visible");
}
}
function addToLocalStorage(id, value) {
const itemsObj = {id: id, value: input.value};
let storageItems = getLocalStorage();
storageItems.push(itemsObj);
localStorage.setItem("list", JSON.stringify(storageItems));
}
function removeFromLocalStorage(id) {
console.log(id);
let storageItems = getLocalStorage();
console.log(storageItems);
storageItems = storageItems.filter(function(singleItem) {
if (singleItem.id !== id) {
return singleItem;
}
})
console.log(storageItems);
localStorage.setItem("list", JSON.stringify(storageItems));
}
function editLocalStorage(id, value) {
}
function getLocalStorage() {
return localStorage.getItem("list") ? JSON.parse(localStorage.getItem("list")) : [];
}
* {
margin: 0;
padding: 0;
}
.app {
width: 70%;
max-width: 600px;
margin: 75px auto 0;
}
.app__title {
text-align: center;
/* color: #1B5D81; */
margin-top: 20px;
color: #377FB4;
}
.app__alert {
width: 60%;
margin: 0 auto;
text-align: center;
font-size: 20px;
color: #215884;
border-radius: 7px;
height: 23px;
transition: 0.4s;
text-transform: capitalize;
}
.app__alert--warning {
background-color: rgba(243, 117, 66, 0.2);
color: #006699;
}
.app__alert--success {
background-color: rgba(165, 237, 92, 0.4);
color: #3333ff;
}
.app__alert--cleared {
background-color: #a978da;
color: white;
}
.app__input-btn-cont {
display: flex;
margin-top: 30px;
}
.app__input {
width: 80%;
box-sizing: border-box;
font-size: 20px;
padding: 3px 0 3px 10px;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
border-right: none;
border: 1px solid #67B5E2;
background-color: #EDF9FF;
}
.app__input:focus {
outline: transparent;
}
.app__submit-btn {
display: block;
width: 20%;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
border-left: none;
background-color: #67B5E2;
border: 1px solid #67B5E2;
cursor: pointer;
font-size: 20px;
color: white;
transition: background-color 0.7s;
padding: 3px 0;
}
.app__submit-btn--edit {
background-color: #95CB5D;
}
.app__submit-btn:active {
width: 19.9%;
padding: 0 0;
}
.app__submit-btn:hover {
background-color: #377FB4;
}
.app__submit-btn--edit:hover {
background-color: #81AF51;
}
.app__items-container {
visibility: hidden;
/* transition: 0.7s; */
}
.app__items-container--visible {
visibility: visible;
}
.app__item {
display: flex;
justify-content: space-between;
margin: 20px 0;
}
.app__item:hover {
background-color: #b9e2fa;
border-radius: 10px;
}
.app__item-text {
padding-left: 10px;
font-size: 20px;
color: #1B5D81;
}
.app__item-btn-cont {
display: flex;
}
.app__item-btn-img {
width: 20px;
height: 20px;
}
.app__item-btn {
border: none;
background-color: transparent;
cursor: pointer;
display: block;
font-size: 18px;
}
.app__item-btn--edit {
margin-right: 45px;
color: #2c800f;
}
.app__item-btn--delete {
margin-right: 15px;
color: rgb(243, 117, 66);
}
.app__clear-btn {
display: block;
width: 150px;
margin: 20px auto;
border: none;
background-color: transparent;
font-size: 20px;
color: rgb(243, 117, 66);
letter-spacing: 2px;
cursor: pointer;
transition: border 0.3s;
border: 1px solid transparent;
}
.app__clear-btn:hover {
border: 1px solid rgb(243, 117, 66);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" name="viewport" content="width=device-width,
initial-scale=1">
<link rel="stylesheet" href="list.css">
<title>To Do List App</title>
</head>
<body>
<section class="app">
<form class="app__form">
<p class="app__alert"></p>
<h2 class="app__title">To Do List</h2>
<div class="app__input-btn-cont">
<input class="app__input" type="text" id="todo" placeholder="do stuff">
<button class="app__submit-btn">Submit</button>
</div>
</form>
<div class="app__items-container">
<div class="app__items-list">
</div>
<button class="app__clear-btn">Clear Items</button>
</div>
</section>
<script src="list.js"></script>
</body>
</html>
Your code is fine you just used the wrong comparison operator.
In your case you are comparing 2 IDs (operands) to see if they match up, so you should use normal operators such as (==, !=), but instead in your case, you have used strict operators which are used to compare the operand type and the operand itself.
You can learn more about Comparison Operators here.
Ultimatly,
In your function removeFromLocalStorage(id), you have an extra equal sign in your if function.
Instead of:
if (singleItem.id !== id) {
return singleItem;}
It should be:
if (singleItem.id != id) {
return singleItem;}
Hope this helps.
I'm trying to fix this error but if i fix have another error with
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);}
i got next error
main.js:297 Uncaught TypeError: Cannot set property 'textContent' of null
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
function updateOutput() {
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
This is code i have problem with (up)
I only want to get after press savebutton all content save.
FULL CODE
function myFunction() {
var x = document.getElementById("Cal");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
var queue = []; // store key history
function getHistory() {
var str = ''
for (var i = 0; i < queue.length; i++)
str += queue[i];
return str;
}
// display functions
function runLB() {
document.case.display.value += "("
queue.push('(')
}
function runRB() {
document.case.display.value += ")"
queue.push(')')
}
function run1() {
document.case.display.value += "1"
queue.push('1')
};
function run2() {
document.case.display.value += "2"
queue.push('2')
};
function run3() {
document.case.display.value += "3"
queue.push('3')
};
function run4() {
document.case.display.value += "4"
queue.push('4')
};
function run5() {
document.case.display.value += "5"
queue.push('5')
};
function run6() {
document.case.display.value += "6"
queue.push('6')
};
function run7() {
document.case.display.value += "7"
queue.push('7')
};
function run8() {
document.case.display.value += "8"
queue.push('8')
};
function run9() {
document.case.display.value += "9"
queue.push('9')
};
function run0() {
document.case.display.value += "0"
queue.push('0')
};
function runPlus() {
document.case.display.value += "+"
queue.push('+')
};
function runMinus() {
document.case.display.value += "-"
queue.push('-')
};
function runDivide() {
document.case.display.value += "/"
queue.push('/')
};
function runMultiply() {
document.case.display.value += "*"
queue.push('*')
};
function runComma() {
document.case.display.value += "."
queue.push('.')
};
function runBack() {
var val = document.case.display.value.slice(0, -1);
document.case.display.value = val;
if (queue.length > 1) {
// pop last element from the array
let last = queue.pop();
// check if element length is more than 1
if (last.length > 1) {
// remove last character from string and push to the array again
queue.push(last.slice(0, -1))
}
}
};
function testLength() {
if (document.case.display.value.length > 16 && document.case.display.value.length < 21) {
document.getElementById("display").style.fontWeight = "550";
document.getElementById("display").style.fontSize = "2em";
} else if (document.case.display.value.length == 16 || document.case.display.value.length == 21) {
Notiflix.Notify.Info('Because you have a lot of charatchers font size is smaller');
} else if (document.case.display.value.length > 25) {
var str = document.case.display.value.length
Notiflix.Notify.Warning('Max characters you can see is 28 ');
Notiflix.Notify.Failure('Number of your characters' + str);
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "1.5em";
} else {
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "2.5em";
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit, #back")
numbers.forEach(el => el.addEventListener('click', testLength))
});
function runEquals() {
if (document.case.display.value.length < 3) {
Notiflix.Notify.Info('Enter charatchers !');
countBell();
} else if (isNaN(document.case.display.value)) {
var equals = Math.round(eval(document.case.display.value) * 1000) / 1000;
document.case.display.value = equals;
document.getElementById("result").innerHTML += queue.join("") + "=" + equals + "\n";
queue = [equals.toString()];
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
Notiflix.Notify.Success('Success');
} else if (document.case.display.value == "Infinity") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Infinity ! ');
countBell();
} else {
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
Notiflix.Notify.Warning(' Can not be calculated ! ');
countBell();
}
}
function testNum() {
if (document.case.display.value == "Infinity") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Infinity ! ');
countBell();
} else if (document.case.display.value == "NaN") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Not a Number ! ');
countBell();
} else if (!document.case.display.value.includes("")) {} else if (document.case.display.value.includes("/0")) {
Notiflix.Notify.Failure(' You cannot divide by 0 ! ');
countBell();
} else if (document.case.display.value.includes("..") || document.case.display.value.includes("//") || document.case.display.value.includes("**") || document.case.display.value.includes("--") || document.case.display.value.includes("++")) {
runBack();
Notiflix.Notify.Failure('Enter number ! ');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")")) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (document.case.display.value.includes(")") && !/([123456789])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value) && !/([123456789])/.test(document.case.display.value)) {} else {
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit, .oper")
numbers.forEach(el => el.addEventListener('click', testNum))
});
Notiflix.Confirm.Init({
timeout: 3000,
okButtonBackground: "#C46600",
titleColor: "#C46600",
});
function DeleteAll() {
document.case.display.value = "";
}
function Del() {
Notiflix.Confirm.Show(' Confirm',
'Are you sure you want to delete text?', 'Yes', 'No',
function() {
Notiflix.Notify.Success('Text is Deleted');
document.getElementById("result").innerHTML = "";
},
function() {
Notiflix.Notify.Info('Text is not Deleted');
countBell();
});
}
//print
function printTextArea() {
childWindow = window.open('', 'childWindow', 'location=yes, menubar=yes, toolbar=yes');
childWindow.document.open();
childWindow.document.write('<html><head></head><body>');
childWindow.document.write(document.getElementById('result').value.replace(/\n/gi, '<br>'));
childWindow.document.write('</body></html>');
childWindow.print();
childWindow.document.close();
childWindow.close();
}
//Font ++ and --
function FontM() {
txt = document.getElementById('result');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
if (currentSize <= 10) {
txt.style.fontSize = (currentSize + 5) + 'px';
Notiflix.Notify.Info('Smallest font size');
} else {
txt.style.fontSize = (currentSize - 5) + 'px';
Notiflix.Notify.Info('Font size -5px');
}
}
//print
function FontP() {
txt = document.getElementById('result');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
if (currentSize >= 50) {
txt.style.fontSize = (currentSize - 5) + 'px';
Notiflix.Notify.Info('Biggest font size');
} else {
txt.style.fontSize = (currentSize + 5) + 'px';
Notiflix.Notify.Info('Font size +5px');
}
}
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);
}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
function updateOutput() {
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
window.onload = function() {
const myInput = document.getElementById('display');
myInput.onpaste = function(e) {
e.preventDefault();
}
}
function Git() {
window.open("https://github.com/TheLexa", "_blank");
countBell()
};
var count = 0;
function countBell() {
setTimeout(function(){
document.getElementById('notification').innerText = '๐';
document.getElementById('notification').style.fontSize = '25px';
setTimeout(function(){
document.getElementById('notification').innerText = x;
document.getElementById('notification').style.fontSize = '33px';
setTimeout(function(){
document.getElementById('notification').innerText = '๐' + x;
document.getElementById('notification').style.fontSize = '22px';
}, 2000);
}, 3000);
}, 2000);
document.getElementById('notification').style.border = "thick solid red ";
count += 1;
notifNote();
}
var x = -1;
function notifNote() {
x++;
if(x==0){
}else{
localStorage.setItem('display_notification' + x, display.value);
localStorage.setItem('x' ,x);
}
}
window.onload = function() {
countBell();
x =+ localStorage.getItem('x');
}
function notif() {
Notiflix.Confirm.Show('Answer', 'Do you want to delete' + ' ' + '(' + x + ')' + ' ' + 'notification', 'Show Notification', 'Yes Delete Notification',
function() {
Notiflix.Report.Success(
' Success', 'We put notification in Note', 'Click');
var note_textarea = document.querySelector('#TE');
var y = 0;
if (x == 0) {
Notiflix.Report.Warning('INFO', 'No notification', 'Click');
} else {
for (y = 1; x > y; y++) {
note_textarea.textContent += '\n' + localStorage.getItem('display_notification' + y) + ' ' + 'Cannot be calculated';
}
note_textarea.textContent += '\n' + localStorage.getItem('display_notification' + y) + ' ' + 'Cannot be calculated';
}
},
function() {
count = 1;
setTimeout(function(){
document.getElementById('notification').innerText = '๐';
document.getElementById('notification').style.fontSize = '25px';
setTimeout(function(){
document.getElementById('notification').innerText = '0';
document.getElementById('notification').style.fontSize = '33px';
setTimeout(function(){
document.getElementById('notification').innerText = '๐';
document.getElementById('notification').style.fontSize = '22px';
}, 2000);
}, 1000);
}, 2000);
var z;
for (z = 0; x > z; z++) {
localStorage.removeItem('display_notification' + z);
}
localStorage.removeItem('display_notification' + z);
x = 0;
Notiflix.Report.Success(
' Success', 'Notification success deleted', 'Click');
});
};
// NUMBERS
/*
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ( (charCode < 40 || charCode > 57)) {
return false;
}
return true;
}
var equal = document.getElementById("equal");
wage.addEventListener("keydown", function (e) {
if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
runEquals();
}
});
*/
#media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
#wrapper {
display: flex;
}
html {
background:
linear-gradient(rgba(196, 102, 0, 0.6), rgba(155, 89, 182, 0.6));
}
ul {
list-style: none;
}
body {
width: 500px;
overflow: hidden;
}
#Print {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 85px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 85px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
}
#Del {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 5px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#Git {
position: absolute;
color: #fff;
background: rgba(255, 110, 0, 0.5);
left: 94.5%;
font-size: 20px;
border-radius: 30px;
width: 80px;
height: 60px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border: 2px solid rgba(255, 110, 0, 0.1);
}
#Note {
border: 3px solid rgba(155, 89, 182, 1);
margin-bottom: 25px;
transform: translate(0, 50%);
width: 401px;
height: 50px;
color: #fff;
font-family: 'Inconsolata', monospace;
font-size: 25px;
text-transform: uppercase;
text-decoration: none;
font-family: sans-serif;
box-sizing: border-box;
background: rgba(155, 89, 182, 1);
background-size: 400%;
border-radius: 0px 0px 7px 7px;
z-index: 1;
}
#Note:hover {
animation: animate 5s linear infinite;
}
#keyframes animate {
0% {
background-position: 0%;
}
100% {
background-position: 500%;
}
}
#Note:before {
content: '';
position: absolute;
top: -5px;
left: -5px;
right: -5px;
bottom: -5px;
z-index: -1;
background: linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);
background-size: 400%;
border-radius: 40px;
opacity: 0;
transition: 0.5s;
}
#Note:hover:before {
filter: blur(20px);
opacity: 1;
animation: animate 5s linear infinite;
}
{}
form {
background: linear-gradient(rgba(196, 102, 0, 0.6), rgba(155, 89, 182, 0.6));
text-align: center;
align-content: center;
border-radius: 10px;
border: 3px solid rgba(196, 102, 0, 0.6);
}
#display {
font-family: 'Roboto', sans-serif;
width: 98%;
height: 60px;
text-align: right;
margin: 5px;
border: 5px solid rgba(196, 102, 0, 0.9);
font-size: 2.5em;
font-weight: 500px;
}
.digit {
font-size: 2rem;
background-color: #f8f8f8;
height: 55px;
width: 22%;
border: 1px solid #c6c6c6;
display: inline-block;
box-shadow: 1px 1px 1px;
color: #222;
font-family: Roboto-Regular, helvetica, arial, sans-serif;
margin: 1.5px;
opacity: 0.9;
box-shadow: 0 1px 1px rgba(0, 0, 0, .1)
}
.oper {
font-size: 2rem;
background-color: #d6d6d6;
height: 55px;
width: 22%;
color: #444;
display: inline-block;
margin: 1.5px;
box-shadow: 0 1px 1px;
font-family: Roboto-Regular, helvetica, arial, sans-serif;
opacity: 0.9;
border: 1px solid #b6b6b6;
box-shadow: 0 1px 1px rgba(0, 0, 0, .1)
}
#equal {
background-color: rgba(196, 102, 0, 0.6);
color: white;
width: 183px;
border: none;
}
#TE {
display: block;
resize: none;
width: 386px;
height: 300px;
margin-top: 5px;
margin-left: 7px;
font-size: 20px;
border: 1px solid rgba(196, 102, 0, 0.9);
border-radius: 0px 0px 10px 10px;
font-family: 'Inconsolata', monospace;
}
#result {
margin-left: 5px;
display: block;
resize: none;
width: 400px;
height: 430px;
max-width: 400px;
max-height: 600px;
font-size: 20px;
border-radius: 10px 10px 1px 1px;
border: 1px solid rgba(196, 102, 0, 0.9);
}
button, input[type=button] {
cursor: pointer;
}
.digit:hover, .oper:hover {
border: 1px solid rgba(0, 0, 0, .1);
box-shadow: 0px 1px 1px rgba(0, 0, 0, .1);
opacity: 1;
}
#Del:hover, #Print:hover, #Git:hover, #FP:hover, #FM:hover, #SaveBtn:hover {
opacity: 0.8;
font-size: 20px;
}
#display:hover {
border: 4px solid rgba(196, 102, 0, 0.9);
}
#FP {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 170px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#FM {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 250px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#SaveBtn {
border: 1px solid rgba(255, 110, 0, 0.7);
background: rgba(200, 102, 0, 0.75);
margin-left: 330px;
position: absolute;
color: white;
font-size: 21px;
width: 75px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
border-radius: 0px 0px 10px 0px;
}
#notification {
border: 3px solid rgba(155, 89, 182, 1);
background: white;
margin-left: 1470px;
margin-top: 730px;
position: absolute;
color: black;
font-size: 22px;
width: 56.5px;
height: 56.5px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
border-radius: 60px 60px 60px 60px;
animation-name: example;
animation-duration: 30s;
}
#keyframes example {
0% {
border-color: red;
}
5% {
border-color: yellow;
}
10% {
border-color: blue;
}
15% {
border-color: green;
}
20% {
border-color: red;
}
25% {
border-color: yellow;
}
30% {
border-color: blue;
}
35% {
border-color: green;
}
40% {
border-color: red;
}
45% {
border-color: yellow;
}
50% {
border-color: blue;
}
55% {
border-color: green;
}
60% {
border-color: red;
}
65% {
border-color: yellow;
}
70% {
border-color: blue;
}
75% {
border-color: green;
}
80% {
border-color: red;
}
85% {
border-color: yellow;
}
90% {
border-color: blue;
}
95% {
border-color: green;
}
100% {
border-color: red;
}
}
<html>
<head>
<!--Copyright 2019, Aleksa Kovacevic, All rights reserved.-->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Online calculators for everything. Some solve problems, some satisfy curiosity." />
<meta name="keywords" content="calculator, mortgage, loan,lease, cooking, math, college tuition, agriculture, finance,fractions,love,scientific, design, health, unit converter, pocket, running, calculators" />
<link rel="icon" href="https://www.apkmirror.com/wp-content/uploads/2017/11/5a0aad10ea5ec.png">
<title id="Title">Calculator </title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" href="main.css" type="text/css">
<link rel="stylesheet" href="Notiflix\node_modules\notiflix\dist\notiflix-1.8.0.min.css" />
<script src="Notiflix\node_modules\notiflix\dist\notiflix-aio-1.8.0.js""></script>
<script src=" main.js" type="text/javascript"></script>
</head>
<body>
<button type="button" id="notification" onclick="notif()"> ๐</button>
<button type="button" id="Git" onclick="Git()"> GitHub</button>
<div id="wrapper">
<form name="case">
<!--Buttons -->
<input name="display" id="display" placeholder "0" onkeypress="" autofocus readonly>
<input type="button" class="oper" value="(" onclick="runLB()">
<input type="button" class="oper" value=")" onclick="runRB()">
<input type="button" id="back" class="oper" value="CE" onclick="runBack()">
<input type="button" id="divide" class="oper" value="รท" onclick="runDivide()">
<input type="button" class="digit" value="1" onclick="run1()">
<input type="button" class="digit" value="2" onclick="run2()">
<input type="button" class="digit" value="3" onclick="run3()">
<input type="button" id="multiply" class="oper" value="ร" onclick="runMultiply()">
<input type="button" class="digit" value="4" onclick="run4()">
<input type="button" class="digit" value="5" onclick="run5()">
<input type="button" class="digit" value="6" onclick="run6()">
<input type="button" id="minus" class="oper" value="-" onclick="runMinus()">
<input type="button" class="digit" value="7" onclick="run7()">
<input type="button" class="digit" value="8" onclick="run8()">
<input type="button" class="digit" value="9" onclick="run9()">
<input type="button" id="plus" class="oper" value="+" onclick="runPlus()">
<input type="button" class="digit" value="0" onclick="run0()">
<input type="button" id="comma" class="digit" value="." onclick="runComma()">
<input type="button" id="equal" class="oper" value="=" onclick="runEquals()">
<div id="Cal">
<textarea id="TE" placeholder="Note"></textarea>
</div>
<div id="newpos">
<!-- button rainbow -->
<button type="button" id="Note" onclick="myFunction()"> Note</button></div>
</form>
<div id="new">
<!--result textarea-->
<textarea id="result" placeholder="History" readonly></textarea>
<button type="button" id="Del" onclick="Del()"> Delete</button>
<button type="button" id="Print" onclick="printTextArea()"> Print</button>
<button type="button" id="FP" onclick="FontP()">Font +</button>
<button type="button" id="FM" onclick="FontM()">Font -</button>
<button type="button" id="SaveBtn"> Save </button>
</div>
</div>
</body>
NOTIFLIX IS library for client-side non-blocking notifications, popup boxes, loading indicators, and more to that makes your web projects much better.
THIS is my portofolio if you have any good information tell me THANKS :)
The problem here is the dom is not loaded so the textarea is not available until the dom is not loaded. adding a window load listener for it will solve it.
window.addEventListener('load', function(){
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);
}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
})
The function does not see the bell variable because a javascript scope does not allow it to be seen. You need to get your dom elements in the inside of the updateOutput function.
function updateOutput() {
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
I am in the process of building a quiz sort of game using JQuery. My game works how I wish it to currently, but only for the first question.
var progress = 0;
var score = 0;
var running = true;
var questions = [
{question: 'Which character is played by Robert Downey Junior?', answers: ['Thor', 'Iron Man', 'Captain America', 'Star Lord'], correct: 'Iron Man'},
{question: 'What colour is the star on Captain Americas shield?', answers: ['Red', 'Silver/Grey', 'Blue', 'Yellow/Gold'], correct: 'Silver/Grey'}
];
var $quiz = $('.quiz');
var $question = $('#quiz-question');
var $answers = $('#answers');
var $next = $('#next');
var $results = $('#results');
var showQuestion = q => {
if (progress < questions.length) {
$question.html(q.question);
$answers.html(' ');
q.answers.forEach(function(ans) {
$answers.append("<div class='answer'>" + ans + "</div>");
})
} else {
$results.html("<h2>Your Results:</h2><p>You scored " + score + "/" + questions.length + "</p>");
$quiz.hide();
$results.show();
}
};
showQuestion(questions[progress]);
$(document).ready(function(){
$next.hide();
$results.hide();
$('.answer').on('click', function(){
if($(this).html() === questions[progress].correct && running) {
progress++;
running = false;
score++;
$(this).css('color', 'green');
$(this).css('border', '3px solid green');
$(this).css('font-weight', 'bold');
$next.show();
} else if ($(this).html() !== questions[progress] && running) {
$(this).css('color', 'red');
$(this).css('border', '3px solid red');
$(this).css('font-weight', 'bold');
progress++;
running = false;
$next.show();
}
})
$next.on('click', function() {
running = true;
showQuestion(questions[progress]);
})
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #c7ecee;
font-family: 'Karla', sans-serif;
}
main {
min-height: 500px;
width: 100%;
display: flex;
align-items: flex-end;
}
main .quiz {
width: 40%;
margin: 0 auto;
text-align: center;
}
main .quiz #quiz-question {
font-size: 2rem;
width: 100%;
border: 2px solid #4d4d4d;
color: #fff;
background-color: #4d4d4d;
padding: 1rem;
}
main .quiz #answers {
font-size: 1.5rem;
border: 1px solid #4d4d4d;
}
main .quiz #answers .answer {
width: 100%;
padding: 1rem;
background-color: #fff;
border: 1px solid #4d4d4d;
cursor: pointer;
}
main .quiz #answers .answer:hover {
}
div#ui {
text-align: center;
width: 100%;
padding: .75rem;
}
div#ui button {
font-size: 1.75rem;
padding: .75rem;
background-color: #4d4d4d;
border: 1px solid #4d4d4d;
color: #fff;
cursor: pointer;
}
<main>
<div class='quiz'>
<div id='quiz-question'>
</div>
<div id='answers'>
</div>
</div>
<div id='results'>
</div>
</main>
<div id='ui'>
<button id='next'>Next</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Basically, a question and its answers are displayed, when an answer is clicked it stops running the game, so that no other answers can be clicked (or an answer can't be clicked more than once to boost score). When the question is answered, a button appears at the bottom to go to the next question. If there are no more questions, it shows you the results display.
This works exactly how I wish - for one question. When I add any further questions, it displays the question exactly as it should, but the on click effects are no longer applied. I assume this is to do with the elements not existing when the $(document).ready() function is called. Could anyone shed any light on how I could solve this problem?
Edited to include code snippet. Uncomment the second quest
On line 37, change:
$('.answer').on('click', function(){
to
$('body').on('click', '.answer', function(){
The thing is, when you write:
$(document).ready(function(){
$next.hide();
$results.hide();
$('.answer').on('click', function(){
You target all elements (at current moment) that have the class .answer. Since this is only the first question (in the beginning) it won't work at the questions after the first one.
If you instead write:
$(document).ready(function(){
$next.hide();
$results.hide();
$('body').on('click', '.answer', function(){
You tell jQuery to add the click-event to any current and new elements that will be added with the class .answer (within the body-element). It better to keep this specific, for example with an id for the quiz.
Se the whole example:
var progress = 0;
var score = 0;
var running = true;
var questions = [
{question: 'Which character is played by Robert Downey Junior?', answers: ['Thor', 'Iron Man', 'Captain America', 'Star Lord'], correct: 'Iron Man'},
{question: 'What colour is the star on Captain Americas shield?', answers: ['Red', 'Silver/Grey', 'Blue', 'Yellow/Gold'], correct: 'Silver/Grey'}
];
var $quiz = $('.quiz');
var $question = $('#quiz-question');
var $answers = $('#answers');
var $next = $('#next');
var $results = $('#results');
var showQuestion = q => {
if (progress < questions.length) {
$question.html(q.question);
$answers.html(' ');
q.answers.forEach(function(ans) {
$answers.append("<div class='answer'>" + ans + "</div>");
})
} else {
$results.html("<h2>Your Results:</h2><p>You scored " + score + "/" + questions.length + "</p>");
$quiz.hide();
$results.show();
}
};
showQuestion(questions[progress]);
$(document).ready(function(){
$next.hide();
$results.hide();
$('body').on('click', '.answer', function(){
if($(this).html() === questions[progress].correct && running) {
progress++;
running = false;
score++;
$(this).css('color', 'green');
$(this).css('border', '3px solid green');
$(this).css('font-weight', 'bold');
$next.show();
} else if ($(this).html() !== questions[progress] && running) {
$(this).css('color', 'red');
$(this).css('border', '3px solid red');
$(this).css('font-weight', 'bold');
progress++;
running = false;
$next.show();
}
})
$next.on('click', function() {
running = true;
showQuestion(questions[progress]);
})
})
<body>
<main>
<div class='quiz'>
<div id='quiz-question'>
</div>
<div id='answers'>
</div>
</div>
<div id='results'>
</div>
</main>
<div id='ui'>
<button id='next'>Next</button>
</div>
<script src='https://code.jquery.com/jquery-3.2.1.min.js' integrity='sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=' crossorigin='anonymous'></script>
<script src='includes/js/main.js'></script>
</body>
Here is a minimal edit to get your code working:
var progress = 0;
var score = 0;
var running = true;
var questions = [
{question: 'Which character is played by Robert Downey Junior?', answers: ['Thor', 'Iron Man', 'Captain America', 'Star Lord'], correct: 'Iron Man'},
{question: 'What colour is the star on Captain Americas shield?', answers: ['Red', 'Silver/Grey', 'Blue', 'Yellow/Gold'], correct: 'Silver/Grey'}
];
var $quiz = $('.quiz');
var $question = $('#quiz-question');
var $answers = $('#answers');
var $next = $('#next');
var $results = $('#results');
var showQuestion = q => {
if (progress < questions.length) {
$question.html(q.question);
$answers.html(' ');
q.answers.forEach(function(ans) {
$answers.append("<div class='answer'>" + ans + "</div>");
})
$('.answer').on('click', function(){
if($(this).html() === questions[progress].correct && running) {
progress++;
running = false;
score++;
$(this).css('color', 'green');
$(this).css('border', '3px solid green');
$(this).css('font-weight', 'bold');
$next.show();
} else if ($(this).html() !== questions[progress] && running) {
$(this).css('color', 'red');
$(this).css('border', '3px solid red');
$(this).css('font-weight', 'bold');
progress++;
running = false;
$next.show();
}
})
} else {
$results.html("<h2>Your Results:</h2><p>You scored " + score + "/" + questions.length + "</p>");
$quiz.hide();
$results.show();
}
};
showQuestion(questions[progress]);
$(document).ready(function(){
$next.hide();
$results.hide();
$next.on('click', function() {
running = true;
showQuestion(questions[progress]);
})
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-color: #c7ecee;
font-family: 'Karla', sans-serif;
}
main {
min-height: 500px;
width: 100%;
display: flex;
align-items: flex-end;
}
main .quiz {
width: 40%;
margin: 0 auto;
text-align: center;
}
main .quiz #quiz-question {
font-size: 2rem;
width: 100%;
border: 2px solid #4d4d4d;
color: #fff;
background-color: #4d4d4d;
padding: 1rem;
}
main .quiz #answers {
font-size: 1.5rem;
border: 1px solid #4d4d4d;
}
main .quiz #answers .answer {
width: 100%;
padding: 1rem;
background-color: #fff;
border: 1px solid #4d4d4d;
cursor: pointer;
}
main .quiz #answers .answer:hover {
}
div#ui {
text-align: center;
width: 100%;
padding: .75rem;
}
div#ui button {
font-size: 1.75rem;
padding: .75rem;
background-color: #4d4d4d;
border: 1px solid #4d4d4d;
color: #fff;
cursor: pointer;
}
<main>
<div class='quiz'>
<div id='quiz-question'>
</div>
<div id='answers'>
</div>
</div>
<div id='results'>
</div>
</main>
<div id='ui'>
<button id='next'>Next</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Basically, you were attaching an event listener to .answer elements once, then replacing those elements, which means when a user clicks the new ones, nothing happens. Here, we add the listeners every time a question is created.
Keep in mind, there are ways you can refactor this code. I would look into event delegation if you want to avoid creating listeners for every .answer element.
I have these elements created inside a "querySelector('ul'). It's working property.
I want the "blue-Save" button to have the same function as the "yellow-Save".
But the Blue-save button was created in the HTML file, and the Yellow-Save button was created in JavaScript to listen to an event from the "querySelector('ul').
Is there anyway I can just link the Blue-Save to react as if I was clicking in the Yellow-Save?
(I'm sorry if I didn't explain it property or If it seems too confused, this is my first application, It doesn't seems too organized but I'm focused in making things work before dive in 'well developed apps').
Thank You Everyone!
var todoList = {
todos: [],
addTodo: function (todoText) {
this.todos.push({
todoText: todoText,
/*the name of the property (even if it is the same name as the parameter) never change. Only the value, which follows in this case is following the parameter*/
completed: false
});
},
changeTodo: function (position, todoText) {
this.todos[position].todoText = todoText;
},
deleteTodo: function (position) {
this.todos.splice(position, 1);
},
toggleCompleted: function (position) {
var todo = this.todos[position];
todo.completed = !todo.completed;
/*Here we flip the boolean to his oposite value. if todo.completed is equal false, so changes it to true, and so on. */
},
toggleAll: function () {
// recording the number of todos and completed todos
var totalTodos = this.todos.length;
var completedTodos = 0;
// get the number of completed todos.
this.todos.forEach(function (todo) {
if (todo.completed === true) {
completedTodos++;
}
});
this.todos.forEach(function (todo) {
// Case 1: If everything is true, make everything.
if (completedTodos === totalTodos) {
todo.completed = false;
// Case 2: Otherwise, make everything true.
} else {
todo.completed = true;
}
});
}
};
var handlers = {
addTodo: function () {
var addTodoTextInput = document.getElementById('add-todo-text-input');
todoList.addTodo(addTodoTextInput.value);
addTodoTextInput.value = '';
view.displayTodos();
},
changeTodo: function (position) {
var changeTodoTextInput = document.getElementById('change-todo-text-input');
todoList.changeTodo(position, changeTodoTextInput.value);
changeTodoTextInput.value = '';
view.displayTodos();
},
deleteTodo: function (position) {
todoList.deleteTodo(position);
view.displayTodos();
},
toggleCompleted: function (position) {
todoList.toggleCompleted(position);
view.displayTodos();
},
toggleAllButton: function () {
todoList.toggleAll();
view.displayTodos();
}
};
var view = {
displayTodos: function () {
var todosUl = document.querySelector('ul');
todosUl.innerHTML = '';
todoList.todos.forEach(function (todo, position) {
var todoLi = document.createElement('li');
var todoTextWithCompletion = '';
if (todo.completed === true) {
todoTextWithCompletion = todo.todoText;
todoLi.classList.add('item-completed');
} else {
todoTextWithCompletion = todo.todoText;
}
todoLi.id = position;
todoLi.textContent = todoTextWithCompletion;
todoLi.appendChild(this.createEditButton());
todoLi.appendChild(this.createToggleButton());
todoLi.appendChild(this.createDeleteButton());
todoLi.appendChild(this.createSaveButton());
todosUl.appendChild(todoLi);
}, this);
},
createDeleteButton: function () {
var deleteButton = document.createElement('button');
deleteButton.textContent = '\u2715';
deleteButton.className = 'delete-button';
return deleteButton;
},
createToggleButton: function () {
var toggleButton = document.createElement('button');
toggleButton.textContent = '\u2713';
toggleButton.className = 'toggle-button';
return toggleButton;
},
createSaveButton: function () {
var saveButton = document.createElement('button');
saveButton.textContent = 'Save';
saveButton.className = 'save-button';
return saveButton;
},
createEditButton: function () {
var editButton = document.createElement('button');
editButton.textContent = '\u270E';
editButton.className = 'edit-button';
return editButton;
},
setUpEventListeners: function () {
var todosUl = document.querySelector('ul');
todosUl.addEventListener('click', function (event) {
// Get the element that was clicked on.
var elementClicked = event.target;
// Check if elementClicked is a delete button.
if (elementClicked.className === 'delete-button') {
handlers.deleteTodo(parseInt(elementClicked.parentNode.id));
} else if (elementClicked.className === 'toggle-button') {
handlers.toggleCompleted(parseInt(elementClicked.parentNode.id));
} else if (elementClicked.className === 'save-button') {
handlers.changeTodo(parseInt(elementClicked.parentNode.id));
} else if (elementClicked.className === 'edit-button') {
}
});
}
};
view.setUpEventListeners();
body {
font-family: Helvetica, sans-serif;
font-size: 25px;
background: rgb(236, 236, 236);
}
h1 {
color: rgb(255, 255, 255);
text-align: center;
font-family: Helvetica, sans-serif;
font-size: 50px;
text-transform: uppercase;
background: rgb(48, 48, 48);
position: relative;
}
.container {
margin: auto;
width: 50%;
}
ul {
list-style: none;
padding:0px;
margin: 10px;
}
.add-button {
background-color: rgb(68, 165, 230); /* Blue */
border: none;
color: white;
margin:auto;
padding: 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 5px;
width:20%;
}
.add-button:hover {
background-color :rgb(53, 127, 177); /* Green */
color: white;
}
.save-change-button {
background-color: rgb(68, 165, 230); /* Blue */
border: none;
color: white;
margin:auto;
padding: 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 5px;
width:20%;
}
.save-change-button:hover {
background-color :rgb(53, 127, 177); /* Green */
color: white;
}
.toggle-all-button {
background-color: rgb(38, 156, 38); /* Green */
border: none;
color: white;
margin: 10px 0;
padding: 15px 32px;
text-align: center;
text-decoration: none;
font-size: 16px;
border-radius: 5px;
width: 100%;
}
.toggle-all-button:hover {
background-color : rgb(36, 114, 36); /* Green */
color: white;
}
.edit-button {
background-color: rgb(219, 208, 50); /* Green */
border: none;
color: white;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 25px;
height: 25px;
margin: 0 0 0 10px;
}
.edit-button:hover {
background-color: rgb(185, 175, 26); /* Green */
color: white;
}
.toggle-button {
background-color: rgb(38, 156, 38); /* Green */
border: none;
color: white;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 25px;
height: 25px;
margin: 0 0 0 10px;
}
.toggle-button:hover {
background-color: rgb(36, 114, 36); /* Green */
color: white;
}
.delete-button {
background-color: rgb(168, 44, 44); /* Green */
border: none;
color: white;
margin: 0 0 0 10px;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 25px;
height: 25px;
}
.delete-button:hover {
background-color :rgb(128, 31, 31); /* Green */
color: white;
}
.save-button {
background-color: rgb(219, 208, 50); /* Green */
border: none;
color: white;
padding: 0;
text-align: center;
text-decoration: none;
font-size: 18px;
border-radius: 5px;
width: 55px;
height: 25px;
margin: 0 10px;
}
.save-button:hover {
background-color :rgb(185, 175, 26); /* Green */
color: white;
}
.add-input {
margin: 10px 0;
padding: 6px 0;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 18px;
width: 78%;
}
.edit-input {
margin: 10px 0;
padding: 6px 0;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 18px;
width: 78%;
}
.item-completed {
text-decoration: line-through;
}
::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
color: rgba(209, 209, 209, 0.555);
font-family: 'Times New Roman', Times, serif;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Todo List</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>Todo List</h1>
<div>
<input id="add-todo-text-input" class="add-input" placeholder="Add a New Todo to Your List" type="text">
<button class="add-button" onclick="handlers.addTodo()">Add</button>
</div>
<ul>
</ul>
<div id="edit-todo"">
<input id="change-todo-text-input" class="edit-input" placeholder="Add the Changes Your Want to Make" type="text">
<button class="save-change-button">Save</button>
</div>
<div id="toggle-all"">
<button class="toggle-all-button" onclick="handlers.toggleAllButton()">Toggle All</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
You can add a common class to both blue and yellow buttons, and attach a click event by the class name like below
$(".custom_save_button").on("click", function() {
//your code
});
Since you are creating that button, sharing the same class won't just work as expected, instead use delegated events which allow you to attach events on new elements added to the DOM
Add a common class for both and then add an event listener for that class using event delegation.
For this example Let's suppose you chose the class name: stack_class
//I added this function for you to be able to know if an element has a class
function hasClass( target, className ) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}
//you could change body to the closest parent's selector both buttons share
document.querySelector('body').addEventListener('click', function(event) {
var clickedElement = event.target;
if(hasClass(clickedElement, "stack_class")) {
//create your functionality for both buttons here
}
});
If you assign a common class to both buttons, then you can add the same event listener to all buttons that have that class. Here is a simple example:
var saveButton = document.createElement('button');
saveButton.textContent = 'Save';
saveButton.className = 'save-button yellow-button';
body = document.querySelector('body');
body.appendChild(saveButton);
buttons = document.getElementsByClassName('save-button');
for (var i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener('click', function (event) {
alert('Hello!');
});
}
.yellow-button {
background: #ffff00;
}
.blue-button {
background: #0000ff;
}
<button class="save-button blue-button">Save</button>