I am stuck in a logical problem.
I have an array where i am stacking items with array.push() where came up from a user's Input.
Problem is now:
How can i print these items to the DOM? ATM i am doing this,
function getInput(operator, description, value) {
// SAVE IN INCOME IF "+" IS CHOOSEN (DEFAULT)
if (addType.value == 'inc') {
let op = incomeArr['operator'] = operator;
let des = incomeArr['description'] = description;
let val = incomeArr['value'] = value;
incomeArr.push([op, des, val]);
return incomeArr;
}
}
Creating a associative array in the getInput();
First attempt to print this data into the DOM looked like this:
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
for (var i = 0; i < expenseArr.length; i++) {
incomeItemSpan;
incomeList.append(incomeItemSpan);
}
}
My problem here is that my forLoop index condition is messing up because of the "everytime function call" the value which is printed out will be printed twice in the next function call of this. the index start again at 0 and even with a out of function loop counter this will not work.
[![gave-input][1]][1]
So the next attempt was:
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
incomeArr.forEach(() => {
incomeList.innerHTML = incomeItemSpan;
});
}
i tried it with a forEach and the problem here is, i have absolutely no idea how to print out the incomeItemSpan without a innerHTML. I want a list of items in the DOM which are stacked from top down, every line is a new item from the array like i would use item.append(), but HTML wont work in a append().
How can i do this?
/* TODO:
- Add Eventlistener for Submit a +/- Value
- if + {add 1. into INCOME section} + Set INCOME in header to the amount
of all incomes added
if - {same like if+ just for -}
- create a update DOM function to update the visualisation of the calculations
- INCOME AND EXPENSES should be a Array
- add a prototype function to remove entrys from INCOME and EXPENSES, use
indexOf to get the index item and remove with array.splice().
- calc every expense with INCOME to get a % value of how much this entry is
% related to the max INCOME
*/
// VARS:
let addType = document.querySelector('.add__type');
let description = document.querySelector('.add__description');
let addValue = document.querySelector('.add__value');
let incomeArr = [];
let expenseArr = [];
// EVENTLISTENER Constructor:
function EventListner(selector, listner, fnt) {
this.selector = selector;
this.listner = listner;
this.fnt = fnt;
document.querySelector(selector).addEventListener(listner, fnt);
};
// getInput VALUES FROM USER Constructor:
function getInput(operator, description, value) {
// SAVE IN INCOME IF "+" IS CHOOSEN (DEFAULT)
if (addType.value == 'inc') {
let op = incomeArr['operator'] = operator;
let des = incomeArr['description'] = description;
let val = incomeArr['value'] = value;
incomeArr.push([op, des, val]);
// TODO: WHAT AFTER SAVING?
return incomeArr;
}
// SAVE IN EXPENSE IF "-" IS CHOOSEN
if (addType.value == 'exp') {
let op = expenseArr['operator'] = operator;
let des = expenseArr['description'] = description;
let val = expenseArr['value'] = value;
expenseArr.push([op, des, val]);
// TODO: WHAT AFTER SAVING?
return expenseArr;
}
};
// STUCK AS FUCK!
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
incomeArr.forEach(() => {
incomeList.innerHTML = incomeItemSpan;
});
// for (var i = 0; i < incomeArr.length; i++) {
// console.log([i]);
// incomeItemSpan;
// incomeList.append(incomeItemSpan);
// }
// console.log(incomeItemSpan);
//
// incomeList.append(expenseArr);
// incomeArr.toString();
// expenseArr.toString();
// incomeList.innerHTML = incomeItemSpan;
};
const main = (function() {
// EVENTLISTENERS
const clickListener = new EventListner('.add__btn', 'click', () => {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
getInput(addType.value, description.value, addValue.value);
});
const enterKeyListener = new EventListner('.add__value', 'keypress', (e) => {
let testArray = [];
for (var i = 0; i < testArray.length; i++) {
testArray[i] = [i];
console.log(testArray[i]);
}
testArray.push('item');
if (e.keyCode == 13) {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
// ON ENTER SAVE VALUES IN AN ARRAY
// IF PLUS INTO incomeArr, ON MINUS INTO expenseArr
// getInput(addType.value, description.value, addValue.value);
printToDOM(getInput(addType.value, description.value, addValue.value));
}
});
}());
//
/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
color: #555;
font-family: Open Sans;
font-size: 16px;
position: relative;
height: 100vh;
font-weight: 400;
}
.right { float: right; }
.red { color: #FF5049 !important; }
.red-focus:focus { border: 1px solid #FF5049 !important; }
/**********************************************
*** TOP PART
**********************************************/
.top {
height: 40vh;
background-image: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url(back.png);
background-size: cover;
background-position: center;
position: relative;
}
.budget {
position: absolute;
width: 350px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
}
.budget__title {
font-size: 18px;
text-align: center;
margin-bottom: 10px;
font-weight: 300;
}
.budget__value {
font-weight: 300;
font-size: 46px;
text-align: center;
margin-bottom: 25px;
letter-spacing: 2px;
}
.budget__income,
.budget__expenses {
padding: 12px;
text-transform: uppercase;
}
.budget__income {
margin-bottom: 10px;
background-color: #28B9B5;
}
.budget__expenses {
background-color: #FF5049;
}
.budget__income--text,
.budget__expenses--text {
float: left;
font-size: 13px;
color: #444;
margin-top: 2px;
}
.budget__income--value,
.budget__expenses--value {
letter-spacing: 1px;
float: left;
}
.budget__income--percentage,
.budget__expenses--percentage {
float: left;
width: 34px;
font-size: 11px;
padding: 3px 0;
margin-left: 10px;
}
.budget__expenses--percentage {
background-color: rgba(255, 255, 255, 0.2);
text-align: center;
border-radius: 3px;
}
/**********************************************
*** BOTTOM PART
**********************************************/
/***** FORM *****/
.add {
padding: 14px;
border-bottom: 1px solid #e7e7e7;
background-color: #f7f7f7;
}
.add__container {
margin: 0 auto;
text-align: center;
}
.add__type {
width: 55px;
border: 1px solid #e7e7e7;
height: 44px;
font-size: 18px;
color: inherit;
background-color: #fff;
margin-right: 10px;
font-weight: 300;
transition: border 0.3s;
}
.add__description,
.add__value {
border: 1px solid #e7e7e7;
background-color: #fff;
color: inherit;
font-family: inherit;
font-size: 14px;
padding: 12px 15px;
margin-right: 10px;
border-radius: 5px;
transition: border 0.3s;
}
.add__description { width: 400px;}
.add__value { width: 100px;}
.add__btn {
font-size: 35px;
background: none;
border: none;
color: #28B9B5;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1.1;
margin-left: 10px;
}
.add__btn:active { transform: translateY(2px); }
.add__type:focus,
.add__description:focus,
.add__value:focus {
outline: none;
border: 1px solid #28B9B5;
}
.add__btn:focus { outline: none; }
/***** LISTS *****/
.container {
width: 1000px;
margin: 60px auto;
}
.income {
float: left;
width: 475px;
margin-right: 50px;
}
.expenses {
float: left;
width: 475px;
}
h2 {
text-transform: uppercase;
font-size: 18px;
font-weight: 400;
margin-bottom: 15px;
}
.icome__title { color: #28B9B5; }
.expenses__title { color: #FF5049; }
.item {
padding: 13px;
border-bottom: 1px solid #e7e7e7;
}
.item:first-child { border-top: 1px solid #e7e7e7; }
.item:nth-child(even) { background-color: #f7f7f7; }
.item__description {
float: left;
}
.item__value {
float: left;
transition: transform 0.3s;
}
.item__percentage {
float: left;
margin-left: 20px;
transition: transform 0.3s;
font-size: 11px;
background-color: #FFDAD9;
padding: 3px;
border-radius: 3px;
width: 32px;
text-align: center;
}
.income .item__value,
.income .item__delete--btn {
color: #28B9B5;
}
.expenses .item__value,
.expenses .item__percentage,
.expenses .item__delete--btn {
color: #FF5049;
}
.item__delete {
float: left;
}
.item__delete--btn {
font-size: 22px;
background: none;
border: none;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1;
display: none;
}
.item__delete--btn:focus { outline: none; }
.item__delete--btn:active { transform: translateY(2px); }
.item:hover .item__delete--btn { display: block; }
.item:hover .item__value { transform: translateX(-20px); }
.item:hover .item__percentage { transform: translateX(-20px); }
.unpaid {
background-color: #FFDAD9 !important;
cursor: pointer;
color: #FF5049;
}
.unpaid .item__percentage { box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1); }
.unpaid:hover .item__description { font-weight: 900; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:100,300,400,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Budgety</title>
</head>
<body>
<div class="top">
<div class="budget">
<div class="budget__title">
Available Budget in <span class="budget__title--month">%Month%</span>:
</div>
<div class="budget__value">+ 0</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 0</div>
<div class="budget__income--percentage"> </div>
</div>
</div>
<div class="budget__expenses clearfix">
<div class="budget__expenses--text">Expenses</div>
<div class="right clearfix">
<div class="budget__expenses--value">- 0</div>
<div class="budget__expenses--percentage">0%</div>
</div>
</div>
</div>
</div>
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
<div class="container clearfix">
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!-- <div class="item clearfix" id="income-0">
<div class="item__description"></div>
<div class="right clearfix">
<div class="item__value"></div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div> -->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
Is that exactly what you're looking for?
const arr = new Array();
function addList() {
const el = document.querySelector("input[name=user]")
const val = el.value
arr.push(val);
el.value = null;
return false;
}
function showList() {
for (let i = 0; i < arr.length; i++) {
const listElement = document.createElement("li");
listElement.textContent = arr[i]
document.body.appendChild(listElement);
}
}
<form onsubmit="return addList()">
<input type="text" name="user">
<button>Add list item</button>
</form><br>
<button class="showList" onclick="showList()">Show list</button>
<ul class="list"></ul>
For creating a list of items, create a ordered/unordered list then append each item to this list in forEach and finally set the html to ordered//unordered list.
Example:
var ol=$('<ol></ol>');
incomeArr.forEach(() => {
ol.append($('<li></li>').text(`${item.description}: ${item.value}`));
});
$('#display').html(ol);
Related
The blue F turns into an actual amount of weight when you enter a number into the input field above.
The Two Functions Kg() and Lbs() are changing the class .dynamic which is where Kg or Lbs is being appended to the 8 divs that have the .dynamic class. Now that's exactly what isn't happening. When I select the divs with the .dynamic class, It adds Kg or Lbs (whatever button I press) to the first element with the .dynamic class.
How do I make it so that it appends that to all of the elements with the .dynamic class?
//Variables
const mercury = document.getElementById("mercury");
const venus = document.getElementById("venus");
const earth = document.getElementById("earth");
const mars = document.getElementById("mars");
const jupiter = document.getElementById("jupiter");
const saturn = document.getElementById("saturn");
const uranus = document.getElementById("uranus");
const neptune = document.getElementById("neptune");
const weight = document.getElementById("weight");
weight.addEventListener("input", Calc);
function Calc() {
if (weight.value > 99999) {
alert("Max Amount Of Numbers is 99999");
weight.value = "";
} else {
var val = weight.value;
console.log(val);
var calculate = val * 0.38;
calculate = Math.round(calculate);
mercury.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.9;
calculate = Math.round(calculate);
venus.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 1;
calculate = Math.round(calculate);
earth.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.38;
calculate = Math.round(calculate);
mars.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 2.36;
calculate = Math.round(calculate);
jupiter.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.92;
calculate = Math.round(calculate);
saturn.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.89;
calculate = Math.round(calculate);
uranus.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 1.12;
calculate = Math.round(calculate);
neptune.innerHTML = calculate;
console.log(calculate);
}
}
function lbs() {
let unit = document.getElementById("unit");
if (unit == null) {
let newElement = document.createElement("h3");
newElement.setAttribute("class", "value");
newElement.setAttribute("id", "unit");
newElement.textContent = "Lbs";
document.querySelector(".dynamic").appendChild(newElement);
} else {
if (unit.innerHTML == "Kg") {
unit.innerHTML = "Lbs";
}
}
}
function kg() {
let unit = document.getElementById("unit");
if (unit == null) {
let newElement = document.createElement("h3");
newElement.setAttribute("class", "value");
newElement.setAttribute("id", "unit");
newElement.textContent = "Kg";
document.querySelector(".dynamic").appendChild(newElement);
} else {
if (unit.innerHTML == "Lbs") {
unit.innerHTML = "Kg";
}
}
}
#import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap");
#font-face {
font-family: SpaceQuest;
src: url(https://raw.githubusercontent.com/Lemirq/WODP/master/Fonts/SpaceQuest-yOY3.woff);
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
}
::-webkit-scrollbar {
width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
background: url(./dario-bronnimann-hNQwIirOseE-unsplash.jpg);
}
/* Handle */
::-webkit-scrollbar-thumb {
background: rgba(59, 59, 59, 0.741);
border-radius: 200px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: rgb(255, 255, 255);
}
* {
--c-light: #f4f4f4;
--c-dark: #141414;
--c-blue: rgb(10, 132, 255);
--f-body: "Montserrat", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
--trans-ease-in-out: all 0.2s ease-in-out;
color: var(--c-light);
}
body {
background-image: url(https://raw.githubusercontent.com/Lemirq/WODP/master/images/dario-bronnimann-hNQwIirOseE-unsplash.jpg);
margin: 0;
inset: 50px;
font-family: var(--f-body);
}
a {
color: var(--c-light);
text-decoration: none;
}
/***** NAVBAR *****/
.nav-item {
transition: var(--trans-ease-in-out);
}
.ext-link {
cursor: alias;
}
.nav-item:hover {
color: var(--c-dark);
background-color: var(--c-light);
}
.nav-item:hover li {
color: var(--c-dark);
}
.nav-item.icon-link:hover i {
color: var(--c-dark);
}
.nav-item:not(:last-child) {
margin-right: 20px;
}
navbar {
display: flex;
flex-direction: row;
justify-content: end;
align-items: center;
padding: 20px;
}
.nav-item-container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin: 0;
padding: 0;
}
.nav-item {
display: inline-block;
list-style: none;
padding: 10px;
font-size: 20px;
border-radius: 10px;
}
.gh-icon {
font-size: 30px;
}
/***** End NAVBAR *****/
/***** Main *****/
#wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
h1 {
font-family: SpaceQuest, sans-serif;
font-size: 3.5rem;
}
.input-group {
border: 2px var(--c-light) solid;
border-radius: 10px;
/* max-width: 400px; */
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin-top: 50px;
}
[type="number"]:focus {
outline: none;
}
[type="number"] {
font-size: 20px;
padding: 5px;
background-color: rgba(217, 217, 217, 0.2);
border: none;
font-family: var(--f-body);
min-width: 280px;
}
.btn-form {
font-size: 20px;
padding: 5px;
background-color: rgba(217, 217, 217, 0.2);
border: none;
transition: var(--trans-ease-in-out);
cursor: pointer;
font-family: var(--f-body);
}
.btn-form:hover {
background-color: rgba(217, 217, 217, 0.4);
}
.btn-form:first {
border-right: var(--c-light) 1px solid;
}
.input-group-text {
background-color: rgba(217, 217, 217, 0.2);
font-size: 17px;
padding: 7px;
}
/***** End Main *****/
/***** CARDS *****/
.card-container {
margin: 50px;
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
align-items: center;
grid-gap: 10px;
width: calc(100vw - 200px);
}
.card {
background-color: #141414;
width: auto;
height: auto;
border-radius: 10px;
padding: 30px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.175);
}
.planet-info {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.planet {
font-size: 50px;
margin: 0;
text-transform: capitalize;
}
.planet-img {
width: 80px;
height: auto;
margin-right: 30px;
}
[src="./images/planets/Saturn.png"] {
height: 79.25px;
width: auto;
}
.weight {
margin-top: 10px;
text-transform: capitalize;
font-size: 20px;
}
.weight::after {
content: ":";
}
.divider {
height: 1px;
width: 100%;
margin: 20px 0;
background-color: var(--c-light);
}
.value {
font-size: 60px;
color: var(--c-blue);
}
.dynamic>.value:nth-child(2) {
margin-left: 10px;
}
.dynamic {
display: flex;
flex-direction: row;
justify-content: space-between;
}
/***** End CARDS *****/
.input-error {
outline: 1px solid red;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.8.3/font/bootstrap-icons.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<navbar>
<ul class="nav-item-container">
<a target="_blank" class="nav-item ext-link" href="https://lemirq.github.io">
<li>Website</li>
</a>
<a target="_blank" class="nav-item icon-link ext-link" href="https://github.com/Lemirq">
<li><i class="bi bi-github gh-icon"></i></li>
</a>
</ul>
</navbar>
<div id="wrapper">
<h1 id="vs-h1">Your Weight On Different Planets</h1>
<div class="input-group">
<input id="weight" placeholder="Enter your Weight" type="number">
<button id="kg" onclick="kg()" class="btn-form" type="button">Kg</button>
<button id="lbs" onclick="lbs()" class="btn-form" type="button">Lbs</button>
</div>
<div class="card-container">
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Mercury.png" alt="EARTH">
<h3 class="planet">mercury</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="mercury" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Venus.png" alt="EARTH">
<h3 class="planet">venus</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="venus" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Earth.png" alt="EARTH">
<h3 class="planet">earth</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="earth" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Mars.png" alt="EARTH">
<h3 class="planet">mars</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="mars" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Jupiter.png" alt="EARTH">
<h3 class="planet">jupiter</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="jupiter" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Saturn.png" alt="EARTH">
<h3 class="planet">saturn</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="saturn" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Uranus.png" alt="EARTH">
<h3 class="planet">uranus</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="uranus" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Neptune.png" alt="EARTH">
<h3 class="planet">neptune</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="neptune" class="value">F</h3>
</div>
</div>
</div>
</div>
Select all elements with the .dynamic class by using querySelectorAll
Iterate through the NodeList and append desired child to each node
let dynamics = document.querySelectorAll(".dynamic")
dynamics.forEach((ele) => {
let newElement = document.createElement("h3");
ele.appendChild(newElement);
}
Minor Problems
There's no such HTML element <navbar>, there's <nav>.
There's a block code hard-coded 8 times with the only difference between them is a number. Whenever code needs to repeat itself, we use some sort of iteration such as a for loop or an array method and the numbers would be passed as a single variable passed with every iteration.
const gforce = [0.38, 0.9, 1, 0.38, 2.36, 0.92, 0.89, 1.12];
for (let i=0; i < 8; i++) {
var val = weight.value;
console.log(val);
var calculate = val * gforce[i];//<== that should be a variable
calculate = Math.round(calculate);
venus.innerHTML = calculate;
console.log(calculate);
}
Also, the <input> that's supposed to calculate lbs and kg doesn't appear to convert kg to lbs or vice-versa.
Details are commented in example
// An array of objects - each object represents a planet
const data = [{
planet: 'Mercury',
gforce: 0.38,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Mercury_in_true_color.jpg/440px-Mercury_in_true_color.jpg`
},
{
planet: 'Venus',
gforce: 0.9,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Venus_from_Mariner_10.jpg/440px-Venus_from_Mariner_10.jpg`
},
{
planet: 'Earth',
gforce: 1,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/c/cb/The_Blue_Marble_%28remastered%29.jpg/440px-The_Blue_Marble_%28remastered%29.jpg`
},
{
planet: 'Mars',
gforce: 0.38,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/OSIRIS_Mars_true_color.jpg/440px-OSIRIS_Mars_true_color.jpg`
},
{
planet: 'Jupiter',
gforce: 2.36,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Jupiter_and_its_shrunken_Great_Red_Spot.jpg/440px-Jupiter_and_its_shrunken_Great_Red_Spot.jpg`
},
{
planet: 'Saturn',
gforce: 0.92,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Saturn_during_Equinox.jpg/600px-Saturn_during_Equinox.jpg`
},
{
planet: 'Uranus',
gforce: 0.89,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/Uranus_as_seen_by_NASA%27s_Voyager_2_%28remastered%29.png/440px-Uranus_as_seen_by_NASA%27s_Voyager_2_%28remastered%29.png`
},
{
planet: 'Neptune',
gforce: 1.12,
img: `https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/Neptune_-_Voyager_2_%2829347980845%29_flatten_crop.jpg/440px-Neptune_-_Voyager_2_%2829347980845%29_flatten_crop.jpg`
}
];
// Reference <form> and all form controls
const conv = document.forms.converter;
const IO = conv.elements;
/*
Collect all tags with [name='planet'] and convert it into an array...
...iterate through array and define a htmlString and interpolate planet
name and <img> url...
...render htmlString into current <output>
*/
[...IO.planet].forEach((output, index) => {
const html = `
<h3>${data[index].planet}</h3>
<img src='${data[index].img}'>
<h4></h4>`;
output.insertAdjacentHTML('beforeend', html)
});
// Bind the "input" event to <form>
conv.oninput = IWC;
/*
Event handler passes Event Object by default
Reference all form controls
Reference the tag the user interacted with
If the user typed into [name='weight']...
...if that tag was also #lbs...
...#kg value is the value of >origin< times 0.45359237...
...otherwise #lbs value is the value of >origin< times 2.20462...
*/
/*
Collect all [name='planet'] into an array and iterate with .forEach()...
...clear out the last tag of current <output> (<h4>)...
...display the calculated totals for lbs. and kg of each planet
*/
function IWC(e) {
const IO = this.elements;
const origin = e.target;
if (origin.name === 'weight') {
if (origin.id === 'lbs') {
IO.kg.value = +origin.value * 0.45359237;
} else {
IO.lbs.value = +origin.value * 2.20462;
}
[...IO.planet].forEach((output, index) => {
output.lastElementChild.innerHTML = '';
output.lastElementChild.insertAdjacentHTML('beforeend',
`lbs. ${Math.round(data[index].gforce * IO.lbs.value)}<br>
kg ${Math.round(data[index].gforce * IO.kg.value)}`);
});
}
}
#import url('https://fonts.googleapis.com/css2?family=Oswald:wght#300&family=Raleway:wght#300&display=swap');
html {
font: 300 2ch/1 Oswald;
}
body {
width: 100%;
overflow-x: hidden;
background: #aaa
}
h1 {
color: gold
}
h1,
h2,
h3,
h4 {
margin: 0;
font-family: Raleway;
}
h3,
h4 {
position: absolute;
z-index: 1;
}
h3 {
margin: 0 auto;
}
h4 {
bottom: 0
}
form {
margin: 0 0 0 -15px;
}
fieldset {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
max-width: 90%;
margin: 15px
}
fieldset+fieldset {
background: #222
}
fieldset+fieldset legend {
color: gold
}
output {
position: relative;
display: inline-flex;
width: 24%;
min-height: 8rem;
margin-top: 15px;
padding: 2px;
background: black;
color: cyan
}
input {
font: inherit;
width: 10rem;
margin: 10px;
text-align: center;
}
img {
width: 100%;
}
<form id='converter'>
<fieldset>
<legend>
<h1>Interplanetary<br>Weight Converter</h1>
</legend>
<input id="lbs" name='weight' placeholder=" Weight in lbs." type="number" min='0' max='99999'><label for='lbs'>lbs.</label>
<input id="kg" name='weight' placeholder="Weight in kg." type="number" min='0' max='99999'><label for='kg'>kg</label>
</fieldset>
<fieldset>
<legend>
<h2>The Solar System</h2>
</legend>
<output name='planet'></output>
<output name='planet'></output>
<output name='planet'></output>
<output name='planet'></output>
<output name='planet'></output>
<output name='planet'></output>
<output name='planet'></output>
<output name='planet'></output>
</fieldset>
</form>
The script must look something like this:
<script>
let elements = document.querySelectorAll(".dynamic")
elements.forEach(el=>{
let child = document.createElement('div')
el.appendChild(child)
})
</script>
This can be simplified quite a bit, the buttons' innerHTML values match what you want in the new unit elements.
<button id="kg" class="btn-form" type="button">Kg</button>
<button id="lbs" class="btn-form" type="button">Lbs</button>
Use JavaScript to add an event listener to both unit buttons that call the same function which will update the innerHTML of the unit headings to match the clicked button. When initializing the unit heading elements you should not give them all the same id but rather a common class and you must also append a cloned copy of the element or it will just move the element form one spot to the next:
document.querySelectorAll('#kg, #lbs').forEach(ub => ub.addEventListener('click', units));
function units(e) {
let units = document.querySelectorAll(".value.unit");
if (units.length == 0) {
let newElement = document.createElement("h3");
newElement.setAttribute("class", "value unit");
document.querySelectorAll(".dynamic").forEach((dyn) => {
// append a cloned copy to each, not the same newElement
dyn.appendChild(newElement.cloneNode())
});
// re-run the query to find the newly added nodes
units = document.querySelectorAll(".value.unit");
}
// set the content
units.forEach(unit => unit.innerHTML = e.target.innerHTML);
}
//Variables
const mercury = document.getElementById("mercury");
const venus = document.getElementById("venus");
const earth = document.getElementById("earth");
const mars = document.getElementById("mars");
const jupiter = document.getElementById("jupiter");
const saturn = document.getElementById("saturn");
const uranus = document.getElementById("uranus");
const neptune = document.getElementById("neptune");
const weight = document.getElementById("weight");
weight.addEventListener("input", Calc);
function Calc() {
if (weight.value > 99999) {
alert("Max Amount Of Numbers is 99999");
weight.value = "";
} else {
var val = weight.value;
console.log(val);
var calculate = val * 0.38;
calculate = Math.round(calculate);
mercury.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.9;
calculate = Math.round(calculate);
venus.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 1;
calculate = Math.round(calculate);
earth.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.38;
calculate = Math.round(calculate);
mars.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 2.36;
calculate = Math.round(calculate);
jupiter.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.92;
calculate = Math.round(calculate);
saturn.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 0.89;
calculate = Math.round(calculate);
uranus.innerHTML = calculate;
console.log(calculate);
var val = weight.value;
console.log(val);
var calculate = val * 1.12;
calculate = Math.round(calculate);
neptune.innerHTML = calculate;
console.log(calculate);
}
}
document.querySelectorAll('#kg, #lbs').forEach(ub => ub.addEventListener('click', units));
function units(e) {
let units = document.querySelectorAll(".value.unit");
if (units.length == 0) {
let newElement = document.createElement("h3");
newElement.setAttribute("class", "value unit");
document.querySelectorAll(".dynamic").forEach((dyn) => {
// append a cloned copy to each, not the same newElement
dyn.appendChild(newElement.cloneNode())
});
// re-run the query to find the newly added nodes
units = document.querySelectorAll(".value.unit");
}
// set the content
units.forEach(unit => unit.innerHTML = e.target.innerHTML);
}
#import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap");
#font-face {
font-family: SpaceQuest;
src: url(https://raw.githubusercontent.com/Lemirq/WODP/master/Fonts/SpaceQuest-yOY3.woff);
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
}
::-webkit-scrollbar {
width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
background: url(./dario-bronnimann-hNQwIirOseE-unsplash.jpg);
}
/* Handle */
::-webkit-scrollbar-thumb {
background: rgba(59, 59, 59, 0.741);
border-radius: 200px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: rgb(255, 255, 255);
}
* {
--c-light: #f4f4f4;
--c-dark: #141414;
--c-blue: rgb(10, 132, 255);
--f-body: "Montserrat", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
--trans-ease-in-out: all 0.2s ease-in-out;
color: var(--c-light);
}
body {
background-image: url(https://raw.githubusercontent.com/Lemirq/WODP/master/images/dario-bronnimann-hNQwIirOseE-unsplash.jpg);
margin: 0;
inset: 50px;
font-family: var(--f-body);
}
a {
color: var(--c-light);
text-decoration: none;
}
/***** NAVBAR *****/
.nav-item {
transition: var(--trans-ease-in-out);
}
.ext-link {
cursor: alias;
}
.nav-item:hover {
color: var(--c-dark);
background-color: var(--c-light);
}
.nav-item:hover li {
color: var(--c-dark);
}
.nav-item.icon-link:hover i {
color: var(--c-dark);
}
.nav-item:not(:last-child) {
margin-right: 20px;
}
navbar {
display: flex;
flex-direction: row;
justify-content: end;
align-items: center;
padding: 20px;
}
.nav-item-container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin: 0;
padding: 0;
}
.nav-item {
display: inline-block;
list-style: none;
padding: 10px;
font-size: 20px;
border-radius: 10px;
}
.gh-icon {
font-size: 30px;
}
/***** End NAVBAR *****/
/***** Main *****/
#wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
h1 {
font-family: SpaceQuest, sans-serif;
font-size: 3.5rem;
}
.input-group {
border: 2px var(--c-light) solid;
border-radius: 10px;
/* max-width: 400px; */
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin-top: 50px;
}
[type="number"]:focus {
outline: none;
}
[type="number"] {
font-size: 20px;
padding: 5px;
background-color: rgba(217, 217, 217, 0.2);
border: none;
font-family: var(--f-body);
min-width: 280px;
}
.btn-form {
font-size: 20px;
padding: 5px;
background-color: rgba(217, 217, 217, 0.2);
border: none;
transition: var(--trans-ease-in-out);
cursor: pointer;
font-family: var(--f-body);
}
.btn-form:hover {
background-color: rgba(217, 217, 217, 0.4);
}
.btn-form:first {
border-right: var(--c-light) 1px solid;
}
.input-group-text {
background-color: rgba(217, 217, 217, 0.2);
font-size: 17px;
padding: 7px;
}
/***** End Main *****/
/***** CARDS *****/
.card-container {
margin: 50px;
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
align-items: center;
grid-gap: 10px;
width: calc(100vw - 200px);
}
.card {
background-color: #141414;
width: auto;
height: auto;
border-radius: 10px;
padding: 30px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.175);
}
.planet-info {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.planet {
font-size: 50px;
margin: 0;
text-transform: capitalize;
}
.planet-img {
width: 80px;
height: auto;
margin-right: 30px;
}
[src="./images/planets/Saturn.png"] {
height: 79.25px;
width: auto;
}
.weight {
margin-top: 10px;
text-transform: capitalize;
font-size: 20px;
}
.weight::after {
content: ":";
}
.divider {
height: 1px;
width: 100%;
margin: 20px 0;
background-color: var(--c-light);
}
.value {
font-size: 60px;
color: var(--c-blue);
}
.dynamic>.value:nth-child(2) {
margin-left: 10px;
}
.dynamic {
display: flex;
flex-direction: row;
justify-content: space-between;
}
/***** End CARDS *****/
.input-error {
outline: 1px solid red;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.8.3/font/bootstrap-icons.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<navbar>
<ul class="nav-item-container">
<a target="_blank" class="nav-item ext-link" href="https://lemirq.github.io">
<li>Website</li>
</a>
<a target="_blank" class="nav-item icon-link ext-link" href="https://github.com/Lemirq">
<li><i class="bi bi-github gh-icon"></i></li>
</a>
</ul>
</navbar>
<div id="wrapper">
<h1 id="vs-h1">Your Weight On Different Planets</h1>
<div class="input-group">
<input id="weight" placeholder="Enter your Weight" type="number">
<button id="kg" class="btn-form" type="button">Kg</button>
<button id="lbs" class="btn-form" type="button">Lbs</button>
</div>
<div class="card-container">
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Mercury.png" alt="EARTH">
<h3 class="planet">mercury</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="mercury" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Venus.png" alt="EARTH">
<h3 class="planet">venus</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="venus" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Earth.png" alt="EARTH">
<h3 class="planet">earth</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="earth" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Mars.png" alt="EARTH">
<h3 class="planet">mars</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="mars" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Jupiter.png" alt="EARTH">
<h3 class="planet">jupiter</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="jupiter" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Saturn.png" alt="EARTH">
<h3 class="planet">saturn</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="saturn" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Uranus.png" alt="EARTH">
<h3 class="planet">uranus</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="uranus" class="value">F</h3>
</div>
</div>
<div class="card">
<div class="planet-info">
<img class="planet-img" src="./images/planets/Neptune.png" alt="EARTH">
<h3 class="planet">neptune</h3>
</div>
<div class="divider"></div>
<h4 class="weight">weight</h4>
<div class="dynamic">
<h3 id="neptune" class="value">F</h3>
</div>
</div>
</div>
</div>
Hi so I have this "product" page (on Fiddle) where I have multiple radio boxes in two classes .choosesize and .choosetea. I want to set up my code where if the 8oz radio button is selected then one set of pictures will appear for all the tea selections and if the 16oz radio button is selected another set of pictures will appear for the tea selections.
I have assigned the small and big images to each tea option but I do not know how to show the small pictures if the small 8oz option is selected.
While you don't have all the "combined" images, I have added a possible solution.
var size = "small"
var teatype = "green"
$('.choosetea input').on('click', function() {
teatype = $(this).attr('data-image');
console.log(size + "_" +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size + "_" +teatype + ']').addClass('active');
$(this).addClass('active');
});
$('.choosesize input').on('click', function() {
size = $(this).attr('data-image');
console.log(size + "_" +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size + "_" +teatype + ']').addClass('active');
$(this).addClass('active');
});
So this will comebine size and teatype, So each image will have the data-image where it should be size_teatype
$(document).ready(function() {
var size = "small"
var teatype = ""
$('.choosetea input').on('click', function() {
teatype = "_"+$(this).attr('data-image');
console.log(size +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size +teatype + ']').addClass('active');
$(this).addClass('active');
});
$('.choosesize input').on('click', function() {
size = $(this).attr('data-image');
console.log(size +teatype)
$('.active').removeClass('active');
$('.columnleft img[data-image = ' + size +teatype + ']').addClass('active');
$(this).addClass('active');
});
//local storage color
//local storage size
// add the value of the added radio boxes in the text box
$('.radios1').change(function(e) {
var selectedValue = parseInt($(this).val());
selectedValue += parseInt($(".radios2").val());
$('#amount').val('$' + selectedValue)
});
//add to cart
});
const sizeSelector = 'input:radio[id=small]';
const colorSelector = 'input:radio[id=green]';
const cartSelector = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const SMALL = 20;
const GREEN = 0;
const CARTBUTTON = 5;
function validityCheck() {
let $size = $(`${sizeSelector}`);
let $color = $(`${colorSelector}`);
let size_flag = $size.is(':checked');
let color_flag = $color.is(':checked');
$('#itemdv1A').toggle(size_flag && color_flag) && $('#itemdv2A').toggle(size_flag && color_flag) && $('#yourbutton').toggle(size_flag && color_flag);
}
});
const sizeSelector1 = 'input:radio[id=small]';
const colorSelector1 = 'input:radio[id=chamomile]';
const cartSelector1 = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const CHAMOMILE = 1;
function validityCheck() {
let $size1 = $(`${sizeSelector1}`);
let $color1 = $(`${colorSelector1}`);
let size_flag1 = $size1.is(':checked');
let color_flag1 = $color1.is(':checked');
$('#itemdv1B').toggle(size_flag1 && color_flag1) && $('#itemdv2B').toggle(size_flag1 && color_flag1) && $('#yourbutton').toggle(size_flag1 && color_flag1)
};
});
const sizeSelector2 = 'input:radio[id=small]';
const colorSelector2 = 'input:radio[id=oolong]';
const cartSelector2 = 'button[name=cart]';
$(function() {
$(`${cartSelector}`).click(() => {
validityCheck();
});
const OOLONG = 2;
function validityCheck() {
let $size2 = $(`${sizeSelector2}`);
let $color2 = $(`${colorSelector2}`);
let size_flag2 = $size2.is(':checked');
let color_flag2 = $color2.is(':checked');
$('#itemdv1C').toggle(size_flag2 && color_flag2) && $('#itemdv2C').toggle(size_flag2 && color_flag2) && $('#yourbutton').toggle(size_flag2 && color_flag2);
}
});
document.querySelector('#yourbutton').onclick = function() {
document.querySelector('#itemscart').style.display = "none"
};
/* Basic Styling */
.container {
width: 1200px;
top: 300px;
left: 50px;
padding: 15px;
display: flex;
position: absolute;
}
/* Columns */
.columnleft {
width: 220%;
position: relative;
margin-left: 30px;
}
.columnright {
width: 120%;
top: 10px;
margin-left: 80px;
display: block;
}
/* Left Column */
.columnleft img {
width: 100%;
position: absolute;
opacity: 0;
transition: all 0.3s ease;
}
.columnleft img.active {
opacity: 1;
}
/* Product Description */
.product-description {
border-bottom: 1px solid #E1E8EE;
margin-bottom: 20px;
}
/* Product Color */
.tea-type {
margin-bottom: 30px;
}
.choosetea div {
display: block;
margin-top: 10px;
}
.label {
width: 150px;
float: left;
text-align: left;
padding-right: 9px;
}
.choosetea input {
display: none;
}
.choosetea input+label span {
display: inline-block;
width: 40px;
height: 40px;
margin: -1px 4px 0 0;
vertical-align: middle;
cursor: pointer;
border-radius: 50%;
}
.choosetea input+label span {
border: 4px solid RGB(94, 94, 76)
}
.choosetea input#green+label span {
background-color: #90978b;
}
.choosetea input#chamomile+label span {
background-color: #ffd4a1;
}
.choosetea input#oolong+label span {
background-color: #948e9e;
}
.choosetea input:checked+label span {
background-image: url(check-icn.svg);
background-repeat: no-repeat;
background-position: center;
}
/* SIZE */
.tea-type {
margin-bottom: 30px;
}
.choosesize div {
display: block;
margin-top: 10px;
}
.label {
width: 100px;
float: left;
text-align: left;
padding-right: 9px;
}
.choosesize input {
display: none;
}
.choosesize input+label span {
display: inline-block;
width: 40px;
height: 40px;
margin: -1px 4px 0 0;
vertical-align: middle;
cursor: pointer;
border-radius: 50%;
}
.choosesize input+label span {
border: 4px solid RGB(94, 94, 76)
}
.choosesize input#small+label span {
background-color: #252525;
}
.choosesize input#big+label span {
background-color: #1d1d1d;
}
.choosesize input:checked+label span {
background-image: url(https://noychat.github.io/Folia-Website/check-icn.svg);
background-repeat: no-repeat;
background-position: center;
}
/* Product Price */
.product-price {
margin-top: 40px;
display: flex;
align-items: center;
}
.product-price span {
font-size: 26px;
font-weight: 300;
color: #43474D;
margin-right: 20px;
}
.cart-btn {
display: inline-block;
background-color: RGB(94, 94, 76);
border-radius: 6px;
font-size: 16px;
color: #FFFFFF;
text-decoration: none;
padding: 12px 30px;
transition: all .5s;
}
.cart-btn:hover {
background-color: black;
}
.cart-btn2 {
background-color: RGB(94, 94, 76);
border-radius: 6px;
font-size: 16px;
color: #FFFFFF;
text-decoration: none;
padding: 12px 30px;
transition: all .5s;
width: 20px;
position: absolute;
}
#amount {
margin-right: 10px;
display: inline-block;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 55px;
height: 40px;
padding-left: 10px;
transition: all .5s;
}
#shoppingcart {
width: 360px;
height: 300px;
/* border: 1px solid red; */
}
.item {
margin-right: 10px;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 200px;
height: 30px;
padding-left: 10px;
transition: all .5s;
float: left;
}
.item1 {
margin-right: 10px;
border-radius: 2px solid RGB(94, 94, 76);
border-radius: 6px;
font-size: 20px;
color: RGB(94, 94, 76);
width: 55px;
height: 30px;
padding-left: 10px;
transition: all .5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header"></div>
<!--close all header portion-->
<div class="container">
<!-- Left Column---Tea Images -->
<div class="columnleft">
<img data-image="oolong" src="https://noychat.github.io/Folia-Website/oolongbig.png" alt=" Big Oolong Can">
<img data-image="chamomile" src="https://noychat.github.io/Folia-Website/chamomilebig.png" alt="Big Chamomile Can">
<img data-image="green" class="active" src="https://noychat.github.io/Folia-Website/greenteabig.png" alt="Big Green Tea Can">
<img data-image="small" class="active" src="https://noychat.github.io/Folia-Website/foliasmall.png" alt="Small Example Can">
<img data-image="big" src="https://noychat.github.io/Folia-Website/foliabig.png" alt="Big Example Can">
<img data-image="small_chamomile" src="https://noychat.github.io/Folia-Website/chamomilesmall.png" alt="Small Chamomile Can">
<img data-image="small_oolong" src="https://noychat.github.io/Folia-Website/oolongsmall.png" alt="Small Oolong Can">
<img data-image="small_green" src="https://noychat.github.io/Folia-Website/greenteasmall.png" alt="Small Green Tea Can">
</div>
<!-- Right Column -->
<div class="columnright">
<!-- Product Description -->
<div class="product-description">
<span>Folia Tea Collection</span>
<h1>Signature Teas</h1>
<p>We source our tea leaves from around the world. Try our many selections of teas and you will taste the difference.</p>
</div>
<!-- Product Configuration -->
<div class="product-configuration">
<!-- Tea Size -->
<div class="tea-type">
<h3>Size</h3>
<div class="choosesize">
<div>
<input data-image="small" type="radio" id="small" name="size" value="20" class="radios1">
<label for="small"><span></span></label>
<div class="label">8 oz</div>
</div>
<div>
<input data-image="big" type="radio" id="big" name="size" value="40" class="radios1">
<label for="big"><span></span></label>
<div class="label">16 oz</div>
</div>
</div>
<!--CLOSE TEA Size-->
<!-- Tea Type -->
<div class="tea-type">
<h3>Tea Type</h3>
<div class="choosetea">
<div>
<input data-image="green" data-image1="small_green" type="radio" id="green" name="color" value="0" class="radios2">
<label for="green"><span></span></label>
<div class="label">Green Tea</div>
</div>
<div>
<input data-image="chamomile" data-image1="small_chamomile" type="radio" id="chamomile" name="color" class="radios2" value="1">
<label for="chamomile"><span></span></label>
<div class="label">Chamomile Tea</div>
</div>
<div>
<input data-image="oolong" data-image1="small_oolong" type="radio" id="oolong" name="color" class="radios2" value="2">
<label for="oolong"><span></span></label>
<div class="label">Oolong Tea</div>
</div>
</div>
</div>
<!--CLOSE TEA TYPE-->
<h3>Product Pricing</h3>
<div class="product-price">
<input type="text" name="amount" id="amount">
<button type="button" class="cart-btn" id="cartbutton" name="cart" value="5">Add To Cart!</button>
</div>
</div>
</div>
<!--close CONTAINER-->
<div id="shoppingcart">
<h3>Shopping Cart</h3>
<h5>Item and Price</h5>
<div id="itemscart">
<div id="itemdv1A" style="display: none"> <input type="text" name="amount" class="item" value="8oz Green Tea"></div>
<div id="itemdv2A" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<div id="itemdv1B" style="display: none"> <input type="text" name="amount" class="item" value="8oz Chamomile Tea"></div>
<div id="itemdv2B" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<div id="itemdv1C" style="display: none"> <input type="text" name="amount" class="item" value="8oz Oolong Tea"></div>
<div id="itemdv2C" style="display: none"> <input type="text" name="amount" class="item1" value="$20"></div>
<button style="display: none" type="button" class="cart-btn2" id="yourbutton" name="remove" value="10">x</button>
</div>
</div>
i'm presently working on a gitHub battle game with JavaScript manipulations. Please, how can i make the "PLAY AGAIN" button restart the game. (Starting All Over Again)
I also want to make the "DIV WITH CONTROL-BUTTON ID" display as block only if data fetch from API was successful.... Thanks
MY CODE IS BELOW:
"use strict";
let user = document.getElementsByClassName('github-username'),
player1 = document.getElementById('player-one'),
player2 = document.getElementById('player-two'),
form1 = document.getElementById('form1'),
form2 = document.getElementById('form2'),
cont1 = document.getElementById('continue1'),
cont2 = document.getElementById('continue2'),
reSelect = document.getElementById('reselect-players'),
playAgain = document.getElementById('play-again'),
initiate = document.getElementById('initiate-battle');
// Function that activate the start button
function getStarted() {
let startPage = document.getElementById('startPage'),
startBtn = document.getElementById('get-started-button');
startBtn.onclick = function() {
startPage.style.display = "none";
player1.style.display = "block";
};
};
getStarted();
// Function that initiates player 1 input
function firstForm() {
player1.style.display = "none";
player2.style.display = "block";
return false;
};
// Function that initiates player 2 input
function secondForm() {
let confirmPage = document.getElementById('confirm-page');
player2.style.display = "none";
confirmPage.style.display = "block";
// Function that fetches users data from input
function fetchUsers() {
let user1, user2;
fetch("https://api.github.com/users/" + user[0].value)
.then(function(response) {
return response.json();
})
.then(function(data) {
// Log the data to the console
console.log(data);
// Cache the data to a variable
user1 = data;
let myUser1 = document.getElementById('user1-container'),
totalScore = (1 * user1.followers + 1 * user1.following + 0.5 * user1.public_repos);
myUser1.innerHTML = `<ul class="user-info">
<p id="firstPlayer"> Player 1 </p>
<li id="score">Score: <span class="totalScr"> ${totalScore}</span> </li>
<li><img class="avatar" src="${user1.avatar_url}"></li>
<li>Name: ${user1.name} </li>
<li>Username: ${user1.login} </li>
<li>Following: ${user1.following} </li>
<li>Followers: ${user1.followers} </li>
<li>Repository: ${user1.public_repos} </li>
</ul>`;
//Make another API call and pass it into the stream
return fetch("https://api.github.com/users/" + user[1].value)
.then(function(response) {
//Get a JSON object from the response
return response.json();
})
})
.then(function(data) {
//Log the data to the console
console.log(data);
// Cache the data to a variable
user2 = data;
//Now that you have both APIs back, you can do something with the data
let myUser2 = document.getElementById('user2-container'),
totalScore2 = (1 * user2.followers + 1 * user2.following + 0.5 * user2.public_repos);
myUser2.innerHTML = `<ul class="user-info">
<p id="secondPlayer"> Player 2 </p>
<li id="score2">Score: <span class="totalScr"> ${totalScore2}</span> </li>
<li><img class="avatar" src="${user2.avatar_url}"></li>
<li>Name: ${user2.name} </li>
<li>Username: ${user2.login} </li>
<li>Following: ${user2.following} </li>
<li>Followers: ${user2.followers} </li>
<li>Repository: ${user2.public_repos} </li>
</ul>`;
})
};
fetchUsers();
setTimeout(function() {
document.getElementById('control-buttons').style.display = "block";
playAgain.style.display = "none";
}, 1500);
return false;
};
//Function that assign users score and winner
initiate.onclick = function() {
document.getElementById("confirm-players").innerHTML = "Winner";
document.getElementById('score').style.display = "block";
document.getElementById('score2').style.display = "block";
initiate.style.display = "none";
reSelect.style.display = "none";
playAgain.style.display = "block";
let totalScr = document.getElementsByClassName("totalScr"),
totalScr1 = parseFloat(totalScr[0].innerText),
totalScr2 = parseFloat(totalScr[1].innerText);
if (totalScr1 > totalScr2) {
document.getElementById("firstPlayer").innerHTML = "Winner";
document.getElementById("secondPlayer").innerHTML = "Loser";
} else if (totalScr1 < totalScr2) {
document.getElementById("firstPlayer").innerHTML = "Loser";
document.getElementById("secondPlayer").innerHTML = "Winner";
} else {
confirm("IT'S A TIE, PLAY AGAIN");
};
};
reSelect.onclick = function() {
confirmPage.style.display = "none";
player1.style.display = "block";
user[0].value = null;
user[1].value = null;
};
playAgain.onclick = function() {
//Make this function start the game again, following the usual pattern
};
body {
margin: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif, cursive;
background-image: url('images/photo.jpg');
background-size: 100%;
background-repeat: no-repeat;
}
input[type=text] {
-moz-box-sizing: border-box;
box-sizing: border-box;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.3);
border: 1px solid #999;
margin: 50px 0 15px;
}
.body-container {
margin: 0;
text-align: center;
}
.body-container p {
font-size: 16px;
padding-bottom: 5px;
}
.head-text {
padding-top: 60px;
margin-bottom: -10px;
font-size: 36px;
}
#confirm-players {
font-size: 30px;
margin: 10px 0 5px;
}
#get-started-button {
font-size: 18px;
font-weight: 10%;
border: none;
width: 150px;
word-spacing: 2px;
border-radius: 5px;
height: 40px;
background-color: green;
color: white
}
.continue-button {
font-size: 18px;
word-spacing: 2px;
border: none;
width: 200px;
border-radius: 5px;
height: 40px;
background-color: green;
color: white
}
#get-started-button:hover,
.continue-button:hover,
#initiate-battle:hover {
background-color: darkgreen;
}
.github-username {
width: 65%;
height: 35px;
padding: 10px;
margin: 20px 0 15px;
}
#score,
#score2 {
font-size: 18px;
font-weight: bolder;
display: none;
text-align: center;
}
#player-one,
#player-two {
display: none;
}
#confirm-page,
#winner {
display: none;
margin: 20px 0 10px;
}
#initiate-battle,
#play-again {
font-size: 18px;
border: none;
width: 200px;
border-radius: 5px;
word-spacing: 2px;
letter-spacing: 0.4px;
height: 40px;
background-color: green;
color: white;
margin: 15px auto 5px;
}
#reselect-players {
font-size: 18px;
border: none;
word-spacing: 2px;
letter-spacing: 0.4px;
width: 240px;
border-radius: 5px;
height: 35px;
background-color: cornflowerblue;
color: white;
margin: 10px auto;
}
#control-buttons {
display: none;
}
#reselect-players:hover {
background-color: darkslateblue;
}
.avatar {
border-radius: 50%;
height: 200px;
width: 200px;
}
.myUsers {
display: inline-block;
margin: 0 5px 0 10px;
}
ul {
margin-left: -30px;
}
li {
list-style: none;
padding: 5px;
text-align: left;
border: 1px solid grey;
}
#firstPlayer,
#secondPlayer {
margin-bottom: 0;
}
<DOCTYPE! html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="githstyle.css" type="text/css">
</head>
<body>
<div id="startPage" class="body-container">
<h1 class="head-text">GitHub Challenge</h1>
<p>Some challenges are worth engaging 🤓</p>
<button id="get-started-button">Get Started</button>
</div>
<div id="player-one" class="body-container">
<h1 class="head-text">Player One</h1>
<div class="form-container">
<form id="form1" onsubmit="return firstForm();">
<div>
<input type="text" class="github-username" placeholder="Enter Player's GitHub Username" required>
</div>
<div>
<input type="submit" value="Continue" id="continue1" class="continue-button">
</div>
</form>
</div>
</div>
<div id="player-two" class="body-container">
<h1 class="head-text">Player Two</h1>
<div class="form-container">
<form id="form2" onsubmit="return secondForm()">
<div>
<input type="text" name="" class="github-username" placeholder="GitHub Username" required>
</div>
<div>
<input type="submit" value="Continue" id="continue1" class="continue-button">
</div>
</form>
</div>
</div>
<div id="confirm-page" class="body-container">
<h1 id="confirm-players">Confirm players</h1>
<div id="user1-container" class="myUsers">
</div>
<div id="user2-container" class="myUsers">
</div>
<div id="control-buttons">
<div>
<button id="initiate-battle">Initiate Battle</button>
</div>
<div>
<button id="reselect-players">Reselect Players</button>
</div>
<div>
<button id="play-again">Play Again</button>
</div>
</div>
</div>
<script src="gith.js" type="text/javascript">
</script>
</body>
</html>
Reloading the page using JavaScript is very easy.
You can achieve this by using location.reload()
If you want to achieve reloading using a button, then be sure to add a return false; right after you call location.reload() to prevent bubbling (parents of the button won't know the event occurred).
So, your code will look something like this :
document.getElementById('yourButton').addEventListener('click', function(){
location.reload();
return false;
});
Hope this helps ! :)
So I have this code for a budget app that I'm doing on a javascript course on Udemy. There's a function to delete the item from the data structure, from the UI and to update the budget. It works fine until when I delete the last item from the list i.e the last item on the array, it deletes the item from the data array and from the UI, but don't recalculate the budget.
I tried to look up into my code, and didn't found anything, so that's why I need you, more experienced guys help :)
// BUDGET CONTROLLER
var budgetController = (function() {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
}
var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
}
var calculateTotal = function(type) {
var sum = 0;
data.allItems[type].forEach(function(cur) {
sum += cur.value;
data.totals[type] = sum;
})
}
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
}
return {
addItem: function(type, des, val) {
var newItem, ID;
// Create a new ID
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
// Create a new item object
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// Push the created object into the data structure
data.allItems[type].push(newItem);
// Return the newItem publicly
return newItem;
},
deleteItem: function(type, id) {
var ids, index;
ids = data.allItems[type].map(function(current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function() {
// Calc total income and expenses
calculateTotal('exp');
calculateTotal('inc');
// Calc the budget(income - expenses)
data.budget = data.totals.inc - data.totals.exp;
// Calc the percentage of income spent
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
} else {
data.percentage = -1;
}
},
getBudget: function() {
return {
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage
}
},
testing: function() {
console.log(data);
}
}
})();
// UI CONTROLLER
var UIController = (function() {
var DOMStrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expensesLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
container: '.container'
}
return {
getInput: function() {
return {
type: document.querySelector(DOMStrings.inputType).value, // Will be inc or exp
description: document.querySelector(DOMStrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMStrings.inputValue).value)
}
},
addListItem: function(obj, type) {
var html, newHtml, element;
// Create HTML string with placeholder text
if (type === 'inc') {
element = DOMStrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
} else if (type === 'exp') {
element = DOMStrings.expensesContainer;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>'
}
// Replace placeholder with actual data
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', obj.value);
// Insert HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteListItem: function(selectorID) {
var el = document.getElementById(selectorID);
el.parentNode.removeChild(el);
},
clearFields: function() {
var fields, fieldsArr;
fields = document.querySelectorAll(DOMStrings.inputDescription + ', ' + DOMStrings.inputValue);
fieldsArr = Array.prototype.slice.call(fields);
fieldsArr.forEach(function(current, index, array) {
current.value = '';
});
fieldsArr[0].focus();
},
displayBudget: function(obj) {
document.querySelector(DOMStrings.budgetLabel).textContent = obj.budget;
document.querySelector(DOMStrings.incomeLabel).textContent = obj.totalInc;
document.querySelector(DOMStrings.expensesLabel).textContent = obj.totalExp;
if (obj.percentage > 0) {
document.querySelector(DOMStrings.percentageLabel).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMStrings.percentageLabel).textContent = '---';
}
},
getDOMStrings: function() {
return DOMStrings;
}
}
})();
// GLOBAL APP CONTROLLER
var controller = (function(budgetCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMStrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(e) {
if (e.keyCode === 13 || e.which === 13) {
ctrlAddItem();
}
});
document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem);
}
var updateBudget = function() {
// Calculate budget
budgetCtrl.calculateBudget();
// Return the budget
var budget = budgetCtrl.getBudget();
// Display the budget on the UI
UICtrl.displayBudget(budget);
}
var ctrlAddItem = function() {
var input, newItem;
// Get the input data from the form
input = UICtrl.getInput();
if (input.description !== '' && !isNaN(input.value) && input.value > 0) {
// Create a new object with the data
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// Add new item to the UI
UICtrl.addListItem(newItem, input.type);
// Clear the fields
UICtrl.clearFields();
// Calculate and update budget
updateBudget();
}
}
var ctrlDeleteItem = function(event) {
var itemID, splitID, type, ID;
itemID = event.target.parentNode.parentNode.parentNode.parentNode.id;
if (itemID) {
splitID = itemID.split('-');
type = splitID[0];
ID = parseInt(splitID[1]);
// Delete item from the data structure
budgetCtrl.deleteItem(type, ID);
// Delete item from the UI
UICtrl.deleteListItem(itemID);
// Update and show the new budget
updateBudget();
}
}
return {
init: function() {
console.log('The application has started.');
setupEventListeners();
UICtrl.displayBudget({
budget: 0,
totalInc: 0,
totalExp: 0,
percentage: -1
});
}
}
})(budgetController, UIController);
controller.init();
/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
color: #555;
font-family: Open Sans;
font-size: 16px;
position: relative;
height: 100vh;
font-weight: 400;
}
.right {
float: right;
}
.red {
color: #FF5049 !important;
}
.red-focus:focus {
border: 1px solid #FF5049 !important;
}
/**********************************************
*** TOP PART
**********************************************/
.top {
height: 40vh;
background-image: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url(back.png);
background-size: cover;
background-position: center;
position: relative;
}
.budget {
position: absolute;
width: 350px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
}
.budget__title {
font-size: 18px;
text-align: center;
margin-bottom: 10px;
font-weight: 300;
}
.budget__value {
font-weight: 300;
font-size: 46px;
text-align: center;
margin-bottom: 25px;
letter-spacing: 2px;
}
.budget__income,
.budget__expenses {
padding: 12px;
text-transform: uppercase;
}
.budget__income {
margin-bottom: 10px;
background-color: #28B9B5;
}
.budget__expenses {
background-color: #FF5049;
}
.budget__income--text,
.budget__expenses--text {
float: left;
font-size: 13px;
color: #444;
margin-top: 2px;
}
.budget__income--value,
.budget__expenses--value {
letter-spacing: 1px;
float: left;
}
.budget__income--percentage,
.budget__expenses--percentage {
float: left;
width: 34px;
font-size: 11px;
padding: 3px 0;
margin-left: 10px;
}
.budget__expenses--percentage {
background-color: rgba(255, 255, 255, 0.2);
text-align: center;
border-radius: 3px;
}
/**********************************************
*** BOTTOM PART
**********************************************/
/***** FORM *****/
.add {
padding: 14px;
border-bottom: 1px solid #e7e7e7;
background-color: #f7f7f7;
}
.add__container {
margin: 0 auto;
text-align: center;
}
.add__type {
width: 55px;
border: 1px solid #e7e7e7;
height: 44px;
font-size: 18px;
color: inherit;
background-color: #fff;
margin-right: 10px;
font-weight: 300;
transition: border 0.3s;
}
.add__description,
.add__value {
border: 1px solid #e7e7e7;
background-color: #fff;
color: inherit;
font-family: inherit;
font-size: 14px;
padding: 12px 15px;
margin-right: 10px;
border-radius: 5px;
transition: border 0.3s;
}
.add__description {
width: 400px;
}
.add__value {
width: 100px;
}
.add__btn {
font-size: 35px;
background: none;
border: none;
color: #28B9B5;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1.1;
margin-left: 10px;
}
.add__btn:active {
transform: translateY(2px);
}
.add__type:focus,
.add__description:focus,
.add__value:focus {
outline: none;
border: 1px solid #28B9B5;
}
.add__btn:focus {
outline: none;
}
/***** LISTS *****/
.container {
width: 1000px;
margin: 60px auto;
}
.income {
float: left;
width: 475px;
margin-right: 50px;
}
.expenses {
float: left;
width: 475px;
}
h2 {
text-transform: uppercase;
font-size: 18px;
font-weight: 400;
margin-bottom: 15px;
}
.icome__title {
color: #28B9B5;
}
.expenses__title {
color: #FF5049;
}
.item {
padding: 13px;
border-bottom: 1px solid #e7e7e7;
}
.item:first-child {
border-top: 1px solid #e7e7e7;
}
.item:nth-child(even) {
background-color: #f7f7f7;
}
.item__description {
float: left;
}
.item__value {
float: left;
transition: transform 0.3s;
}
.item__percentage {
float: left;
margin-left: 20px;
transition: transform 0.3s;
font-size: 11px;
background-color: #FFDAD9;
padding: 3px;
border-radius: 3px;
width: 32px;
text-align: center;
}
.income .item__value,
.income .item__delete--btn {
color: #28B9B5;
}
.expenses .item__value,
.expenses .item__percentage,
.expenses .item__delete--btn {
color: #FF5049;
}
.item__delete {
float: left;
}
.item__delete--btn {
font-size: 22px;
background: none;
border: none;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1;
display: none;
}
.item__delete--btn:focus {
outline: none;
}
.item__delete--btn:active {
transform: translateY(2px);
}
.item:hover .item__delete--btn {
display: block;
}
.item:hover .item__value {
transform: translateX(-20px);
}
.item:hover .item__percentage {
transform: translateX(-20px);
}
.unpaid {
background-color: #FFDAD9 !important;
cursor: pointer;
color: #FF5049;
}
.unpaid .item__percentage {
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
}
.unpaid:hover .item__description {
font-weight: 900;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:100,300,400,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Budgety</title>
</head>
<body>
<div class="top">
<div class="budget">
<div class="budget__title">
Available Budget in <span class="budget__title--month">%Month%</span>:
</div>
<div class="budget__value">+ 2,345.64</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 4,300.00</div>
<div class="budget__income--percentage"> </div>
</div>
</div>
<div class="budget__expenses clearfix">
<div class="budget__expenses--text">Expenses</div>
<div class="right clearfix">
<div class="budget__expenses--value">- 1,954.36</div>
<div class="budget__expenses--percentage">45%</div>
</div>
</div>
</div>
</div>
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
<div class="container clearfix">
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!--
<div class="item clearfix" id="income-0">
<div class="item__description">Salary</div>
<div class="right clearfix">
<div class="item__value">+ 2,100.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
The problem is that you assign to data.totals[type] = sum; inside the forEach loop in calculateTotal(). If there are no items in the array, the loop never runs, so you never do the assignment.
You don't need to do that assignment each time through the loop, just once after the loop is done calculating the total. So it should be
var calculateTotal = function(type) {
var sum = 0;
data.allItems[type].forEach(function(cur) {
sum += cur.value;
})
data.totals[type] = sum;
}
var calculateTotal = function (type) {
var sum = 0;
data.allItems[type].forEach(function (cur) {
sum += cur.value;
data.totals[type] = sum;
}); };
if the data.allItems doesn't have any value then the total not getting updated.
You have to check if the allItems have 0 then update the totals as 0
i get this error when ever i run this code, try all possible way..any help with this:
Uncaught TypeError: Cannot read property 'length' of undefined at Object.addItem (app.js:41) at HTMLButtonElement.ctrlAddItem
// BUDGET CONTROLLER
var budgetController = (function() {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
};
var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
return {
addItem: function(type, des, val) {
var newItem, ID;
//[1 2 3 4 5], next ID = 6
//[1 2 4 6 8], next ID = 9
// ID = last ID + 1
// Create new ID
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
// Create new item based on 'inc' or 'exp' type
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// Push it into our data structure
data.allItems[type].push(newItem);
// Return the new element
return newItem;
},
testing: function() {
console.log(data);
}
};
})();
// UI CONTROLLER
var UIController = (function() {
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
};
return {
getInput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value, // Will be either inc or exp
description: document.querySelector(DOMstrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMstrings.inputValue).value)
};
},
getDOMstrings: function() {
return DOMstrings;
}
};
})();
// GLOBAL APP CONTROLLER
var controller = (function(budgetCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
};
var ctrlAddItem = function() {
var input, newItem;
// 1. Get the field input data
input = UICtrl.getInput();
// 2. Add the item to the budget controller
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. Add the item to the UI
// 4. Clear the fields
// 5. Calculate and update budget
// 6. Calculate and update percentages
};
return {
init: function() {
console.log('Application has started.');
setupEventListeners();
}
};
})(budgetController, UIController);
controller.init();
/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
color: #555;
font-family: Open Sans;
font-size: 16px;
position: relative;
height: 100vh;
font-weight: 400;
}
.right { float: right; }
.red { color: #FF5049 !important; }
.red-focus:focus { border: 1px solid #FF5049 !important; }
/**********************************************
*** TOP PART
**********************************************/
.top {
height: 40vh;
background-image: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url(back.png);
background-size: cover;
background-position: center;
position: relative;
}
.budget {
position: absolute;
width: 350px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
}
.budget__title {
font-size: 18px;
text-align: center;
margin-bottom: 10px;
font-weight: 300;
}
.budget__value {
font-weight: 300;
font-size: 46px;
text-align: center;
margin-bottom: 25px;
letter-spacing: 2px;
}
.budget__income,
.budget__expenses {
padding: 12px;
text-transform: uppercase;
}
.budget__income {
margin-bottom: 10px;
background-color: #28B9B5;
}
.budget__expenses {
background-color: #FF5049;
}
.budget__income--text,
.budget__expenses--text {
float: left;
font-size: 13px;
color: #444;
margin-top: 2px;
}
.budget__income--value,
.budget__expenses--value {
letter-spacing: 1px;
float: left;
}
.budget__income--percentage,
.budget__expenses--percentage {
float: left;
width: 34px;
font-size: 11px;
padding: 3px 0;
margin-left: 10px;
}
.budget__expenses--percentage {
background-color: rgba(255, 255, 255, 0.2);
text-align: center;
border-radius: 3px;
}
/**********************************************
*** BOTTOM PART
**********************************************/
/***** FORM *****/
.add {
padding: 14px;
border-bottom: 1px solid #e7e7e7;
background-color: #f7f7f7;
}
.add__container {
margin: 0 auto;
text-align: center;
}
.add__type {
width: 55px;
border: 1px solid #e7e7e7;
height: 44px;
font-size: 18px;
color: inherit;
background-color: #fff;
margin-right: 10px;
font-weight: 300;
transition: border 0.3s;
}
.add__description,
.add__value {
border: 1px solid #e7e7e7;
background-color: #fff;
color: inherit;
font-family: inherit;
font-size: 14px;
padding: 12px 15px;
margin-right: 10px;
border-radius: 5px;
transition: border 0.3s;
}
.add__description { width: 400px;}
.add__value { width: 100px;}
.add__btn {
font-size: 35px;
background: none;
border: none;
color: #28B9B5;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1.1;
margin-left: 10px;
}
.add__btn:active { transform: translateY(2px); }
.add__type:focus,
.add__description:focus,
.add__value:focus {
outline: none;
border: 1px solid #28B9B5;
}
.add__btn:focus { outline: none; }
/***** LISTS *****/
.container {
width: 1000px;
margin: 60px auto;
}
.income {
float: left;
width: 475px;
margin-right: 50px;
}
.expenses {
float: left;
width: 475px;
}
h2 {
text-transform: uppercase;
font-size: 18px;
font-weight: 400;
margin-bottom: 15px;
}
.icome__title { color: #28B9B5; }
.expenses__title { color: #FF5049; }
.item {
padding: 13px;
border-bottom: 1px solid #e7e7e7;
}
.item:first-child { border-top: 1px solid #e7e7e7; }
.item:nth-child(even) { background-color: #f7f7f7; }
.item__description {
float: left;
}
.item__value {
float: left;
transition: transform 0.3s;
}
.item__percentage {
float: left;
margin-left: 20px;
transition: transform 0.3s;
font-size: 11px;
background-color: #FFDAD9;
padding: 3px;
border-radius: 3px;
width: 32px;
text-align: center;
}
.income .item__value,
.income .item__delete--btn {
color: #28B9B5;
}
.expenses .item__value,
.expenses .item__percentage,
.expenses .item__delete--btn {
color: #FF5049;
}
.item__delete {
float: left;
}
.item__delete--btn {
font-size: 22px;
background: none;
border: none;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1;
display: none;
}
.item__delete--btn:focus { outline: none; }
.item__delete--btn:active { transform: translateY(2px); }
.item:hover .item__delete--btn { display: block; }
.item:hover .item__value { transform: translateX(-20px); }
.item:hover .item__percentage { transform: translateX(-20px); }
.unpaid {
background-color: #FFDAD9 !important;
cursor: pointer;
color: #FF5049;
}
.unpaid .item__percentage { box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1); }
.unpaid:hover .item__description { font-weight: 900; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:100,300,400,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Budgety</title>
</head>
<body>
<div class="top">
<div class="budget">
<div class="budget__title">
Available Budget in <span class="budget__title--month">%Month%</span>:
</div>
<div class="budget__value">+ 2,345.64</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 4,300.00</div>
<div class="budget__income--percentage"> </div>
</div>
</div>
<div class="budget__expenses clearfix">
<div class="budget__expenses--text">Expenses</div>
<div class="right clearfix">
<div class="budget__expenses--value">- 1,954.36</div>
<div class="budget__expenses--percentage">45%</div>
</div>
</div>
</div>
</div>
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="income" selected>+</option>
<option value="expense">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
<div class="container clearfix">
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!--
<div class="item clearfix" id="income-0">
<div class="item__description">Salary</div>
<div class="right clearfix">
<div class="item__value">+ 2,100.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
// Budget Ctrl
var BudgetCtrl = (function(){
var Expense = function(id, description, value){
this.id = id;
this.description = description;
this.value = value;
}
var Income = function(id, description, value){
this.id = id;
this.description = description;
this.value = value;
};
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
};
return {
addItem: function(type, des, val) {
var newItem, ID;
//[1 2 3 4 5], next ID = 6
//[1 2 4 6 8], next ID = 9
// ID = last ID + 1
// Create new ID
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
// Create new item based on 'inc' or 'exp' type
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// Push it into our data structure
data.allItems[type].push(newItem);
// Return the new element
return newItem;
},
testing: function() {
console.log(data);
}
};
})();
//UI Ctrl
var UIctrl = (function(){
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
};
return {
getInput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value,
//inc or exp
description:
document.querySelector(DOMstrings.inputDescription).value,
value:
document.querySelector(DOMstrings.inputValue).value,
};
},
getDOMstrings: function() {
return DOMstrings;
}
};
})();
//App Ctrl
var ctrl = (function(budgetCtrl, uiCtrl){
var setupEventListener = function(){
var Dom = uiCtrl.getDOMstrings();
document.querySelector(Dom.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(e) {
if(e.keyCode == 13 || e.which === 13) {
ctrlAddItem();
}
});
};
var ctrlAddItem = function() {
var input, newItem;
//1. get the field inpute data
input = uiCtrl.getInput();
//2. add the item to the budget ctrl
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
//3. add item to UI
//4. calculate the budget
//5. display the budget on th UI
};
return {
init: function(){
console.log('app started');
setupEventListener();
}
};
})(BudgetCtrl, UIctrl);
ctrl.init();
I saw a problem on html file with the input options:
<option value ="income" selected>+</option>
<option value ="expense">+</option>
You have to use them in your JS code or try setting in the html: value="inc" and value="exp"
Your option values do not match your object properties. You need to change to:
<option value="inc" selected>+</option>
<option value="exp">-</option>