Increase, decrease and remove buttons do not work properly [duplicate] - javascript
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I would like to increase, decrease and remove items from my cart page but the buttons only work on the first items and the buttons increase the total amount of items in the cart instead of increasing the individual number of items.I would also like to decrease and increase the total amount as I press the buttons.What am I doing wrong? This is my github hosted page for the final result:/my hosted page.
var carts = document.querySelectorAll(".cart-button");
var products = [
{
id: 1,
name: "Brown Brim",
image: "https://i.ibb.co/ZYW3VTp/brown-brim.png",
price: 25,
inCart:0
},
{
id: 2,
name: "Blue Beanie",
image: "https://i.ibb.co/ypkgK0X/blue-beanie.png",
price: 18,
inCart:0
},
{
id: 3,
name: "Brown Cowboy",
image: "https://i.ibb.co/QdJwgmp/brown-cowboy.png",
price: 35,
inCart:0
},
{
id: 4,
name: "Grey Brim",
image:"https://i.ibb.co/RjBLWxB/grey-brim.png",
price: 25,
inCart:0
},
{
id: 5,
name: "Adidas NMD",
image: "https://i.ibb.co/0s3pdnc/adidas-nmd.png",
price: 220,
inCart:0
},
{
id: 6,
name: "Adidas Yeezy",
image:"https://i.ibb.co/dJbG1cT/yeezy.png",
price: 280,
inCart:0
},
{
id: 7,
name: "Black Converse",
image:"https://i.ibb.co/bPmVXyP/black-converse.png",
price: 110,
inCart:0
},
{
id: 8,
name: "Nike White AirForce",
image:"https://i.ibb.co/1RcFPk0/white-nike-high-tops.png",
price: 160,
inCart:0
},
{
id: 9,
name: "Black Jean Shearling",
image:"https://i.ibb.co/XzcwL5s/black-shearling.png",
price: 125,
inCart:0
},
{
id: 10,
name: "Blue Jean Jacket",
image:"https://i.ibb.co/mJS6vz0/blue-jean-jacket.png",
price: 90,
inCart:0
},
{
id: 11,
name: "Grey Jean Jacket",
image:"https://i.ibb.co/N71k1ML/grey-jean-jacket.png",
price: 90,
inCart:0
},
{
id: 12,
name: "Brown Shearling",
image:"https://i.ibb.co/s96FpdP/brown-shearling.png",
price: 165,
inCart:0
},
{
id: 13,
name: "Blue Tanktop",
image:"https://i.ibb.co/7CQVJNm/blue-tank.png",
price: 25,
inCart:0
},
{
id: 14,
name: "Floral Blouse",
image:"https://i.ibb.co/4W2DGKm/floral-blouse.png",
price: 20,
inCart:0
},
{
id: 15,
name: "Floral Dress",
image:"https://i.ibb.co/KV18Ysr/floral-skirt.png",
price: 80,
inCart:0
},
{
id: 16,
name: "Red Dots Dress",
image:"https://i.ibb.co/N3BN1bh/red-polka-dot-dress.png",
price: 80,
inCart:0
},
{
id: 17,
name: "Camo Down Vest",
image:"https://i.ibb.co/xJS0T3Y/camo-vest.png",
price: 325,
inCart:0
},
{
id: 18,
name: "Floral T-shirt",
image:"https://i.ibb.co/qMQ75QZ/floral-shirt.png",
price: 20,
inCart:0
},
{
id: 19,
name: "Black & White Longsleeve",
image:"https://i.ibb.co/55z32tw/long-sleeve.png",
price: 25,
inCart:0
},
{
id: 20,
name: "Pink T-shirt",
image:"https://i.ibb.co/RvwnBL8/pink-shirt.png",
price: 25,
inCart:0
}
];
for (let i = 0; i < carts.length; i++){
carts[i].addEventListener("click", ()=>{
cartNumbers(products[i]);
totalCost(products[i]);
});
}
function onLoadCartNumbers(){
let productNumbers = localStorage.getItem("cartNumbers");
if(productNumbers){
document.querySelector(".item-count").textContent = productNumbers;
}
}
function cartNumbers(product){
let productNumbers = localStorage.getItem("cartNumbers");
productNumbers = parseInt(productNumbers);
if (productNumbers){
localStorage.setItem("cartNumbers", productNumbers + 1);
document.querySelector(".item-count").textContent = productNumbers + 1;
}else {
localStorage.setItem("cartNumbers", 1);
document.querySelector(".item-count").textContent = 1;
}
setItems(product);
}
function setItems(product){
let cartItems = localStorage.getItem("productsInCart");
cartItems = JSON.parse(cartItems);
if(cartItems !== null){
if (cartItems[product.name] === undefined){
cartItems = {
...cartItems,
[product.name]:product
}
}
cartItems[product.name].inCart += 1;
}else{
product.inCart = 1;
cartItems = {
[product.name]:product
}
}
localStorage.setItem("productsInCart",JSON.stringify(cartItems));
}
function totalCost(product){
var cartCost = localStorage.getItem("totalCost");
if(cartCost !== null){
cartCost = parseInt(cartCost);
localStorage.setItem("totalCost", cartCost + product.price);
}else{
localStorage.setItem("totalCost", product.price);
}
}
function displayCart(){
var cartCost = localStorage.getItem("totalCost");
let cartItems = localStorage.getItem("productsInCart");
cartItems = JSON.parse(cartItems);
let productContainer = document.querySelector(".output");
if( cartItems && productContainer ){
productContainer.innerHTML = "";
Object.values(cartItems).map(item =>{
productContainer.innerHTML += `
<div id="cartResult" class="cart-contain">
<div class="cart-header">
<div class="product">
<img src=${item.image}>
</div>
<div class="description">
<p >${item.name}</p></div>
<div class="quantity">
<button onclick="subtract()" class="add"><</button>
<p class="in-cart" id="cartCount">${item.inCart}</p>
<button onclick="add()" class="minus">></button>
</div>
<div class="price"><p>N ${item.price}.00</p></div>
<div class="remove"><button onclick="remove(cartResult)">тип</button></div>
</div>
</div>
`
;
}
);
productContainer.innerHTML += `
<div class="total-container"><h3 class="total-title">TOTAL:</h3>
<h3 class="total">${cartCost}</h3
</div>
`
}
}
function remove() {
let productNumbers = localStorage.getItem("cartNumbers");
var myobj = document.querySelector("#cartResult");
myobj.remove();
}
function add(cartCount)
{
var increase = document.querySelector('.minus');
let productNumbers = localStorage.getItem("item.inCart");
productNumbers = parseInt(productNumbers);
if (productNumbers){
localStorage.setItem("item.inCart", productNumbers + 1);
document.querySelector("#cartCount").textContent = productNumbers + 1;
}else {
localStorage.setItem("item.inCart", 1);
document.querySelector("#cartCount").textContent = 1;
}
setItems(i);
}
function subtract(cartCount)
{
var decrease = document.querySelector('.add');
var productNumbers = localStorage.getItem("item.inCart");
productNumbers = parseInt(productNumbers);
if (productNumbers){
localStorage.setItem("item.inCart", productNumbers - 1);
document.querySelector("#cartCount").innerHTML = productNumbers - 1;
}else {
localStorage.setItem("item.inCart", 1);
document.querySelector("cartCount").textContent = 1;
}
setItems();
}
displayCart();
onLoadCartNumbers();
#import url('https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght#300&display=swap');
*{
box-sizing: border-box;
}
body{
font-family: 'Open Sans Condensed', sans-serif;
margin: 50px;
}
.shopping-icon{
width: 24px;
height: 24px;
}
.cart-icon .item-count{
position: absolute;
font-size: 10px;
font-weight: 700;
bottom: 12px;
}
.cart-icon{
color: #000;
width: 45px;
height: 45px;
position: relative;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
header .option{
width: 100%;
height: 100%;
margin-top: -50px;
display: flex;
align-items: center;
justify-content: flex-end;
}
.collection-item {
width: 22vw;
height: 350px;
align-items: center;
position: relative;
}
.collection-page .items .collection-item {
margin-bottom: 30px;
}
.collection-item .image {
width: 100%;
height: 95%;
background-size: cover;
background-position: 50%;
margin-bottom: 5px;
}
.items{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
align-items: center;
}
.cart-button{
position: relative;
bottom: 110px;
width: 80%;
justify-content: center;
opacity: .7;
left: 10%;
right: 10%;
visibility: hidden ;
height: 50px;
letter-spacing: .5px;
line-height: 50px;
font-family: 'Open Sans Condensed', sans-serif;
font-size: 15px;
font-weight: bolder;
cursor: pointer;
}
#inc{
outline: none;
border: none;
margin-left: 0px;
height: 15px;
width: 10px;
cursor: pointer;
color: transparent;
text-shadow: 0px 1px 0px #000;
}
.collection-item:hover .cart-button{
visibility: visible;
opacity: .9;
border: 1px solid #000;
}
.collection-item:hover .image{
opacity: .7;
}
.cart-button:hover{
background-color: #000;
color: #fff;
border:1px solid #000;
}
.collection-footer{
display: flex;
justify-content: space-between;
}
/*cart page*/
.cart-container{
max-width: 650px;
justify-content: space-around;
margin: 0 auto;
margin-top: 50px;
}
.cart-contain{
max-width: 650px;
justify-content: space-around;
margin: 0 auto;
margin-top: 50px;
}
.cart-heading{
width: 100%;
max-width: 650px;
display: flex;
justify-content: flex-start;
border-bottom: 1px solid #000;
margin: 0 auto;
}
.cart-header{
width: 100%;
max-width: 650px;
display: flex;
justify-content: flex-start;
border-bottom: 1px solid #000;
margin: 0 auto;
}
.product{
width: 30%;
}
.product img{
margin-top: 40px;
height: 200px;
width: 150px;
}
.description{
width: 20%;
display: flex;
align-items: center;
}
.description p{
font-size: 1.3rem;
}
.quantity{
width: 30%;
display: flex;
align-items: center;
display: flex;
justify-content: space-around;
}
.price{
width: 20%;
display: flex;
align-items: center;
}
.price p{
font-size: 1.3rem;
}
.remove{
width: 20%;
display: flex;
align-items: center;
}
.in-cart{
font-size: 1.3rem;
}
.add{
font-size: 30px;
cursor: pointer;
font-weight: bold;
border: none;
background-color: transparent;
outline: none;
}
.minus{
font-size: 30px;
cursor: pointer;
font-weight: bold;
border: none;
background-color: transparent;
outline: none;
}
.remove button{
font-size:30px;
cursor: pointer;
border: none;
background-color: transparent;
outline: none;
}
.test-warning{
text-align: center;
margin-top: 40px;
font-size: 24px;
color: red;
}
.total-container{
display: flex;
justify-content: flex-end;
width: 100%;
padding: 10px 0;
}
.total-title{
width: 20%;
}
.total{
width: 10%;
}
.StripeCheckout{
overflow: hidden;
display: inline-block;
background: linear-gradient(rgb(40, 160, 229), rgb(1, 94, 148));
border: 0px;
padding: 1px;
text-decoration: none;
border-radius: 5px;
box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 0px;
cursor: pointer;
visibility: visible;
user-select: none;
margin-left: 50%;
margin-top: 50px;
}
<!DOCTYPE html>
<html>
<head>
<title>CRWN Clothing</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript"src="index.js"></script>
</head>
<body>
<header>
<div class="logo">
<a class="logo-container" href="index.html">
<svg width="50px" height="39px" viewBox="0 0 50 39" class="logo"><title>Group</title><desc>Created with Sketch.</desc><g id="WiP" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g id="Artboard" transform="translate(-90.000000, -38.000000)"><g id="Group" transform="translate(90.000000, 38.000000)"><polygon id="Rectangle" fill="#808282" points="3 14 25 26.5 47 14 40.855176 39 9.08421785 39"></polygon><polygon id="Triangle" fill-opacity="0.262838724" fill="#101A1A" points="25 8 40 39 10 39"></polygon><circle id="Oval" fill="#5E6363" cx="2" cy="9" r="2"></circle><circle id="Oval" fill="#5E6363" cx="25" cy="2" r="2"></circle><circle id="Oval" fill="#5E6363" cx="48" cy="9" r="2"></circle>
</g></g></g>
</svg>
</a>
</div>
<div class="option" onclick="location.href='./cart.html'">
<div class="cart-icon" onclick="location.href='./cart.html'">
<svg id="Capa_1" x="0px" y="0px" viewBox="0 0 407.453 407.453" xml:space="preserve" class="shopping-icon"><g><path d="M255.099,116.515c4.487,0,8.129-3.633,8.129-8.129c0-4.495-3.642-8.129-8.129-8.129H143.486 c-4.487,0-8.129,3.633-8.129,8.129c0,4.495,3.642,8.129,8.129,8.129H255.099z" style="fill: rgb(1, 0, 2);"></path><path d="M367.062,100.258H311.69c-4.487,0-8.129,3.633-8.129,8.129c0,4.495,3.642,8.129,8.129,8.129h47.243 v274.681H48.519V116.515h44.536c4.487,0,8.129-3.633,8.129-8.129c0-4.495-3.642-8.129-8.129-8.129H40.391 c-4.487,0-8.129,3.633-8.129,8.129v290.938c0,4.495,3.642,8.129,8.129,8.129h326.671c4.487,0,8.129-3.633,8.129-8.129V108.386 C375.191,103.891,371.557,100.258,367.062,100.258z" style="fill: rgb(1, 0, 2);"></path><path d="M282.59,134.796c4.487,0,8.129-3.633,8.129-8.129V67.394C290.718,30.238,250.604,0,201.101,0 c-49.308,0-89.414,30.238-89.414,67.394v59.274c0,4.495,3.642,8.129,8.129,8.129s8.129-3.633,8.129-8.129V67.394 c0-28.198,32.823-51.137,73.36-51.137c40.334,0,73.157,22.939,73.157,51.137v59.274 C274.461,131.163,278.095,134.796,282.59,134.796z" style="fill: rgb(1, 0, 2);"></path><path d="M98.892,147.566c0,11.526,9.389,20.907,20.923,20.907c11.534,0,20.923-9.38,20.923-20.907 c0-4.495-3.642-8.129-8.129-8.129s-8.129,3.633-8.129,8.129c0,2.561-2.089,4.65-4.666,4.65c-2.569,0-4.666-2.089-4.666-4.65 c0-4.495-3.642-8.129-8.129-8.129S98.892,143.071,98.892,147.566z" style="fill: rgb(1, 0, 2);"></path><path d="M282.59,168.473c11.534,0,20.923-9.38,20.923-20.907c0-4.495-3.642-8.129-8.129-8.129 c-4.487,0-8.129,3.633-8.129,8.129c0,2.561-2.089,4.65-4.666,4.65c-2.577,0-4.666-2.089-4.666-4.65 c0-4.495-3.642-8.129-8.129-8.129c-4.487,0-8.129,3.633-8.129,8.129C261.667,159.092,271.055,168.473,282.59,168.473z" style="fill: rgb(1, 0, 2);"></path></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g></svg>
<span class="item-count"> 0 </span>
</div>
</div>
</header>
<main>
<div class="collection-page">
<center><h1>Hats</h1></center>
<div class="items">
<div class="collection-item">
<div class="image" style="background-image: url("https://i.ibb.co/ZYW3VTp/brown-brim.png");"></div><div class="collection-footer"><span class="name">Brown Brim</span><span class="price">N25</span></div>
<button class="cart-button" >Add to cart</button></div>
<div class="collection-item">
<div class="image" style="background-image: url("https://i.ibb.co/ypkgK0X/blue-beanie.png");"></div>
<div class="collection-footer"><span class="name">Blue Beanie</span><span class="price">N18</span></div>
<button class="cart-button" >Add to cart</button></div>
<div class="collection-item">
<div class="image" style="background-image: url("https://i.ibb.co/QdJwgmp/brown-cowboy.png");"></div>
<div class="collection-footer"><span class="name">Brown Cowboy</span><span class="price">N35</span>
</div>
<button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/RjBLWxB/grey-brim.png");"></div>
<div class="collection-footer"><span class="name">Grey Brim</span><span class="price">N25</span></div><button class="cart-button" >Add to cart</button></div></div>
<center><h1 class="title">SNEAKERS</h1></center>
<div class="items">
<div class="collection-item">
<div class="image" style="background-image: url("https://i.ibb.co/0s3pdnc/adidas-nmd.png");"></div>
<div class="collection-footer"><span class="name">Adidas NMD</span><span class="price">N220</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/dJbG1cT/yeezy.png");"></div><div class="collection-footer"><span class="name">Adidas Yeezy</span><span class="price">N280</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/bPmVXyP/black-converse.png");"></div><div class="collection-footer"><span class="name">Black Converse</span><span class="price">N110</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/1RcFPk0/white-nike-high-tops.png");"></div><div class="collection-footer"><span class="name">Nike White AirForce</span><span class="price">N160</span></div><button class="cart-button" >Add to cart</button></div></div>
<center><h1 class="title">JACKETS</h1></center>
<div class="items"><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/XzcwL5s/black-shearling.png");"></div><div class="collection-footer"><span class="name">Black Jean Shearling</span><span class="price">N125</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/mJS6vz0/blue-jean-jacket.png");"></div><div class="collection-footer"><span class="name">Blue Jean Jacket</span><span class="price">N90</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/N71k1ML/grey-jean-jacket.png");"></div><div class="collection-footer"><span class="name">Grey Jean Jacket</span><span class="price">N90</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/s96FpdP/brown-shearling.png");"></div><div class="collection-footer"><span class="name">Brown Shearling</span><span class="price">N165</span></div><button class="cart-button" >Add to cart</button></div></div>
<center><h1 class="title">WOMEN</h1></center>
<div class="items"><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/7CQVJNm/blue-tank.png");"></div><div class="collection-footer"><span class="name">Blue Tanktop</span><span class="price">N25</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/4W2DGKm/floral-blouse.png");"></div><div class="collection-footer"><span class="name">Floral Blouse</span><span class="price">N20</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/KV18Ysr/floral-skirt.png");"></div><div class="collection-footer"><span class="name">Floral Dress</span><span class="price">N80</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/N3BN1bh/red-polka-dot-dress.png");"></div><div class="collection-footer"><span class="name">Red Dots Dress</span><span class="price">N80</span></div><button class="cart-button" >Add to cart</button></div></div>
<center><h1 class="title">MEN</h1></center>
<div class="items">
<div class="collection-item">
<div class="image" style="background-image: url("https://i.ibb.co/xJS0T3Y/camo-vest.png");"></div>
<div class="collection-footer"><span class="name">Camo Down Vest</span><span class="price">N325</span></div>
<button class="cart-button">Add to cart</button></div>
<div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/qMQ75QZ/floral-shirt.png");"></div><div class="collection-footer"><span class="name">Floral T-shirt</span><span class="price">N20</span></div><button class="cart-button" >Add to cart</button></div><div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/55z32tw/long-sleeve.png");"></div><div class="collection-footer"><span class="name">Black & White Longsleeve</span><span class="price">N25</span></div>
<button class="cart-button" >Add to cart</button></div>
<div class="collection-item"><div class="image" style="background-image: url("https://i.ibb.co/RvwnBL8/pink-shirt.png");"></div>
<div class="collection-footer"><span class="name">Pink T-shirt</span><span class="price">N25</span></div>
<button class="cart-button" >Add to cart</button>
</div>
</div>
</div>
</main>
</body>
<script type="text/javascript"src="index.js"></script>
</html>
You are using the cart-contain class to identify an object and remove it. Since you have multiple items with that same class, whenever you click on any 'remove' button, it finds the first item with class cart-contain and removes it.
You want some unique identifier, which you add as an id to every .cart-contain item. Then you can refer to that id when you click remove.
<div id="SOME_ID_HERE" class="cart-contain">
<button onclick="remove(SOME_ID_HERE)">
function remove(id) {
let productNumbers = localStorage.getItem("cartNumbers");
var myobj = document.querySelector(id);
myobj.remove();
}
Related
How to .appendChild() to all elements with the same class
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>
Assign TWO Images to Radio Button
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>
Javascript: Dynamically inserting svgs from an array
Building a quiz, and running into an svg snag. I have a folder full of svgs that I would like to appear in each of the multiple choice options (each svg is specific to each answer). Right now, they're looped through, but I can't get a pathway correct in order for them to appear as the ACTUAL svgs instead of just their name (Q1_A, Q1_B and so on). Thus far I've tried using template literals ( icon.innerHTML = /icons/${questions[choicesCounter].icons['choice' + number]}) as well as just using the pathway (tested with, and w/o "") in the array (choice1:/icons/Q1_A.svg). They all come back as undefined or with some other sort of error. Suggestions? //Questions Array let questions =[ { question:"Do you mind crowds?", icons:{ choice1: "Q1_A.svg", choice2: "Q1_B.svg", choice3: "Q1_C.svg", choice4: "Q1_D.svg", }, choices:{ choice1: "Crowds don't bother me", choice2:"I prefer to get off the beaten path", choice3:"I don't care either way", choice4:"Crowds mean there is something worth looking at", } }, { question:"Where would you like to stay on your trip?", icons:{ choice1:"Q2_A.svg", choice2:"Q2_B.svg", choice3:"Q2_C.svg", choice4:"Q2_D.svg", }, choices:{ choice1:"Hotel", choice2:"Tent", choice3:"RV", choice4:"Cabin" } }, { question:"What activities do you enjoy?", icons:{ choice1:"Q3_A.svg", choice2:"Q3_B.svg", choice3:"Q3_C.svg", choice4:"Q3_D.svg", }, choices:{ choice1: "Animal Watching", choice2:"Hiking", choice3:"Kayaking", choice4:"Biking" } }]; //Convert to an array, so you can use array functions on it const icon= Array.from(document.getElementsByClassName('choice_icon')); const choice= Array.from(document.getElementsByClassName('choice_text')); let choicesCounter=0; //Loop through the arry iconsLoop = () => { icon.forEach(icon => { const number = icon.dataset['number']; icon.innerHTML =questions[choicesCounter].icons['choice' + number]; }); }; iconsLoop(); .multiple-choice-container{ display: flex; flex-wrap: wrap; justify-content:center; } .choice_container{ height: 8rem; width: 7rem; display: flex; flex-direction: column; justify-content:center; align-items: center; font-size: 1rem; text-align: center; margin: 1rem; border: solid #DDDDDD .2px; } .choice_container:hover{ background:#30638E; color: #fdfdfd; border:none; cursor: pointer; transform: translateY(-0.2rem); transition: transform 150ms; box-shadow: 0px 7px 4px 0px rgba(50, 50, 50, 0.75); } .choice_container:hover > .choice_prefix{ cursor: pointer; background: #003D5B; } .choice_container:hover > .choice_text{ color: #fdfdfd; } .choice_icon{ display:flex; justify-content: center; align-items: center; height:4rem; width: 3rem; background:#30638E; color:#fdfdfd; margin-bottom: .5rem; } .choice_text{ margin-left:.5rem; width:100%; border-left: 0; font-size: 1rem; } <div class="choice_container"> <p class="choice_icon" data-number = '1'>A</p> <p class="choice_text" data-number = '1'> Choice 1</p> </div> <div class="choice_container "> <p class="choice_icon" data-number = '2'>B</p> <p class="choice_text" data-number = '2'> Choice 2</p> </div> <div class="choice_container" > <p class="choice_icon" data-number = '3'>C</p> <p class="choice_text" data-number = '3'> Choice 3</p> </div> <div class="choice_container" > <p class="choice_icon" data-number = '4'>D</p> <p class="choice_text" data-number = '4'> Choice 4</p> </div> </div>
Using template literals works, but you need to embed the svg in an img tag if you're setting the innerHTML property. A little hard to demo, but the below should illustrate the point //Questions Array let questions = [{ question: "Do you mind crowds?", icons: { choice1: "Q1_A here", choice2: "Q1_B here", choice3: "Q1_C here", choice4: "Q1_D here", }, choices: { choice1: "Crowds don't bother me", choice2: "I prefer to get off the beaten path", choice3: "I don't care either way", choice4: "Crowds mean there is something worth looking at", } }] //Convert to an array, so you can use array functions on it const icon = Array.from(document.getElementsByClassName('choice_icon')); const choice = Array.from(document.getElementsByClassName('choice_text')); let choicesCounter = 0; //Loop through the arry iconsLoop = () => { icon.forEach(icon => { const number = icon.dataset['number']; icon.innerHTML = `<img src="http://placeholder.pics/svg/100x100/888888/EEE/${questions[choicesCounter].icons['choice' + number]}">`; }); }; iconsLoop(); .multiple-choice-container { display: flex; flex-wrap: wrap; justify-content: center; } .choice_container { height: 8rem; width: 7rem; display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 1rem; text-align: center; margin: 1rem; border: solid #DDDDDD .2px; } .choice_container:hover { background: #30638E; color: #fdfdfd; border: none; cursor: pointer; transform: translateY(-0.2rem); transition: transform 150ms; box-shadow: 0px 7px 4px 0px rgba(50, 50, 50, 0.75); } .choice_container:hover>.choice_prefix { cursor: pointer; background: #003D5B; } .choice_container:hover>.choice_text { color: #fdfdfd; } .choice_icon { display: flex; justify-content: center; align-items: center; height: 4rem; width: 3rem; background: #30638E; color: #fdfdfd; margin-bottom: .5rem; } .choice_text { margin-left: .5rem; width: 100%; border-left: 0; font-size: 1rem; } <div class="choice_container"> <p class="choice_icon" data-number='1'>A</p> <p class="choice_text" data-number='1'> Choice 1</p> </div> <div class="choice_container "> <p class="choice_icon" data-number='2'>B</p> <p class="choice_text" data-number='2'> Choice 2</p> </div> <div class="choice_container"> <p class="choice_icon" data-number='3'>C</p> <p class="choice_text" data-number='3'> Choice 3</p> </div> <div class="choice_container"> <p class="choice_icon" data-number='4'>D</p> <p class="choice_text" data-number='4'> Choice 4</p> </div> </div>
How do I get my Code to show only one picture per question
const question = document.querySelector('#question'); const choices = Array.from(document.querySelectorAll('.choice-text')); const progressText = document.querySelector('#progressText'); const scoreText = document.querySelector('#score'); let currentQuestion = {} let acceptingAnswers = true let score = 0 let questionCounter = 0 let availableQuestions = [] let questions = [ { question: "Question 1", choice1: "Spain", choice2: "France", choice3: "Colombia", choice4: "China", answer: 2, }, { question:"Question 2", choice1: "Hungary", choice2: "Switzerland", choice3: "Chile", choice4: "Austrailia", answer: 1, }, { question: "Question 3", choice1: "Chile", choice2: "Brazil", choice3: "New Zealand", choice4: "Morocco", answer: 4, }, ] const SCORE_POINTS = 1 const MAX_QUESTIONS = 6 function startGame(){ questionCounter = 0 score = 0 availableQuestions = [...questions] getNewQuestion() } function getNewQuestion(){ if(availableQuestions.length === 0 || questionCounter > MAX_QUESTIONS) { localStorage.setItem('mostRecentScore', score) return window.location.assign('end.html') } questionCounter++ progressText.innerText = `Question ${questionCounter} of ${MAX_QUESTIONS}` // progressBarFull.style.width = `${(questionCounter/MAX_QUESTIONS) * 100}%` const questionsIndex = Math.floor(Math.random() * availableQuestions.length) currentQuestion = availableQuestions[questionsIndex] question.innerText = currentQuestion.question choices.forEach(choice => { const number = choice.dataset['number'] choice.innerText = currentQuestion['choice' + number] }) availableQuestions.splice(questionsIndex, 1) acceptingAnswers = true } choices.forEach(choice => { choice.addEventListener('click', e => { if(!acceptingAnswers) return acceptingAnswers = false const selectedChoice = e.target const selectedAnswer = selectedChoice.dataset['number'] let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect' if(classToApply === 'correct') { incrementScore(SCORE_POINTS) } selectedChoice.parentElement.classList.add(classToApply) setTimeout(() => { selectedChoice.parentElement.classList.remove(classToApply) getNewQuestion() }, 1000) }) }) function incrementScore(num){ score +=num scoreText.innerText = score } startGame() body{ background-color: gray; } *{ box-sizing: border-box; margin: 0; padding: 0; font-size: 62.5%; } h1{ text-align: center; font-size: 5.4rem; color: black; margin-bottom: 5rem; } h2{ font-size: 4.2rem; margin-bottom: 4rem; } .container{ width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; max-width: 80rem; margin: 0 auto; padding: 2rem; } .flex-column{ display: flex; flex-direction: column; } .flex-center{ justify-content: center; align-items: center; } .justify-center{ justify-content: center; } .text-center{ text-align: center; } .hidden{ display: none; } .btn{ font-size: 2.4rem; padding:2rem 0; width: 30rem; text-align: center; margin-bottom: 1rem; text-decoration: none; color: rgb(29, 26, 26); background: lightblue; border-radius: 4px; } .btn:hover{ cursor: pointer; background: teal; box-shadow: rgb(130, 170, 183); transition:transform 150ms; transform: scale(1.03); } .btn[disabled]:hover{ cursor: not-allowed; box-shadow: none; transform: none; } body { color: black; } .choice-container { display: flex; margin-bottom: 0.8rem; width: 100%; border-radius: 4px; background: lightblue; font-size: 3rem; min-width: 80rem; } .choice-container:hover { cursor: pointer; box-shadow: 0 0.4rem 1.4rem 0 rgba(6, 103, 247, 0.5); transform: scale(1.02); transform: transform 100ms; } .choice-prefix { padding: 2rem 2.5rem; color: black } .choice-text { padding: 2rem; width: 100%; } .progressText{ text-align: center; } .correct { background: green; } .incorrect { background: red; } /* Heads up Display */ #hud { display: flex; justify-content: space-between; } .hud-prefix { text-align: center; font-size: 2rem; } .hud-main-text { text-align: center; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Quiz Page</title> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="game.css"> <style> img{ align-self: center; width: 80px; height: 150; padding-bottom: 50px; } </style> </head> <body> <div class="container"> <div id="game" class="justify-center flex-column"> <div id="hud"> <div class="hud-item"> <p id="progressText" class="hud-prefix"> Question </p> <div id="progressBarFull"></div> </div> <div class="hud-item"> <p class="hud-prefix"> Score </p> <h1 class="hud-main-text" id="score"> 0 </h1> </div> </div> <h1 id="question">What is the answer to this question</h1> <img id="france" src="france.jpg"> <img id="hungary" src="hungary.jpg"> <img id="morocco" src="morocco.jpg"> <div class="choice-container"> <p class="choice-prefix">A</p> <p class="choice-text" data-number="1">Choice</p> </div> <div class="choice-container"> <p class="choice-prefix">B</p> <p class="choice-text" data-number="2">Choice 2</p> </div> <div class="choice-container"> <p class="choice-prefix">C</p> <p class="choice-text" data-number="3">Choice 3</p> </div> <div class="choice-container"> <p class="choice-prefix">D</p> <p class="choice-text" data-number="4">Choice 4</p> </div> </div> </div> <script src="Flag.js"></script> </body> </html> Im creating a quiz game that shows the user a country flag and the user has to choose from four choices to pick the correct one. Currently I have all the questions flags being shown because I cant figure out how to show just one image per question. Is there a way to hide the other pictures or put the image to specify an image to a question. The quiz also randomizes each time you play so if the first time you play is different the second time. I added a code snippet of just the flag questions. my entire code as a home page and an end page that shows the final score and lets the user play again.
Here you go: https://codepen.io/chrisbradshaw/pen/yLaLLVo. Remove the flag images from HTML and add: <img src="" alt="quiz show question" id="flagImage" /> Include flag image in question objects: { question: "Question 1", choice1: "Spain", choice2: "France", choice3: "Colombia", choice4: "China", answer: 2, flagImage: 'https://placekitten.com/200/300' } Create a variable for #flagImage DOM img: const flagImageHtml = document.querySelector('#flagImage'); Update the src of the #flagImage DOM img when you change the current question: flagImageHtml.src = currentQuestion.flagImage;
(VUE.js) The event doesn't work when called outside the component
I'm making a small page for the product based on this tutorial. On the page I have a product component, where I keep a "add to cart" button. The card itself, however, is separated from the component and located inside index.html, that's why my cart property is being kept inside vue app (where app is an id of my root div in index.html). Problem: I need my "add to cart" button to increment the number in the cart itself. I can't really understand how can I do this using addToCart and updateCart methods, as shown in the tutorial. Can anyone help me out with this issue? I will appreciate any help! Thanks in advance! Vue.component('product', { props: { premium: { type: Boolean, required: true } }, template: ` <div id="product"> <div class="product-image"> <img :src="image" /> </div> <div class="product-info"> <h1>{{ title }}</h1> <p>Shipping: {{ shipping }}</p> <p v-if="inStock">In Stock</p> <p v-else>Out of Stock</p> <h2>Details</h2> <ul> <li v-for="detail in details">{{ detail }}</li> </ul> <h3>Colors:</h3> <div v-for="(variant,index) in variants" :key="variant.variantId"> <div class="color-box" :style="{ backgroundColor: variant.variantColor }" #mouseover="updateProduct(index)"></div> </div> <button :class="{ disabledButton: !inStock }" v-on:click="add-to-cart" :disabled="!inStock">Add to Cart</button> </div> </div> `, data() { return { product: "Socks", brand: "Vue Mastery", selectedVariant: 0, details: ["80% cotton", "20% polyester", "Gender-neutral"], variants: [ { variantId: 2234, variantQuantity: 15, variantColor: "green", variantImage: "./assets/vmSocks-green.jpg" }, { variantId: 2235, variantQuantity: 0, variantColor: "blue", variantImage: "./assets/vmSocks-blue.jpg" } ] } }, methods: { addToCart() { this.$emit('add-to-cart') }, updateProduct(index) { this.selectedVariant = index } }, computed: { title() { return this.brand + ' ' + this.product }, image() { return this.variants[this.selectedVariant].variantImage }, inStock() { if (this.variants[this.selectedVariant].variantQuantity > 0) { return true } else { return false } }, shipping() { if (this.premium) { return "Free" } else { return 2.99 } } } }) var app = new Vue({ el: '#app', data: { premium: true, cart: 0 }, methods: { updateCart() { this.cart += 1 } } }) body { font-family: tahoma; color:#282828; margin: 0px; } .nav-bar { background: linear-gradient(-90deg, #84CF6A, #16C0B0); height: 60px; margin-bottom: 15px; } .product { display: flex; flex-flow: wrap; padding: 1rem; } img { border: 1px solid #d8d8d8; width: 70%; margin: 40px; box-shadow: 0px .5px 1px #d8d8d8; } .product-image { width: 80%; } .product-image, .product-info { margin-top: 10px; width: 50%; } .color-box { width: 40px; height: 40px; margin-top: 5px; } .cart { margin-right: 25px; float: right; border: 1px solid #d8d8d8; padding: 5px 20px; } button { margin-top: 30px; border: none; background-color: #1E95EA; color: white; height: 40px; width: 100px; font-size: 14px; } .disabledButton { background-color: #d8d8d8; } .review-form { width: 400px; padding: 20px; margin: 40px; border: 1px solid #d8d8d8; } input { width: 100%; height: 25px; margin-bottom: 20px; } textarea { width: 100%; height: 60px; } .tab { margin-left: 20px; cursor: pointer; } .activeTab { color: #16C0B0; text-decoration: underline; } <!DOCTYPE html> <html> <head> <meta name="viewpoint" content="width=devide-width, initial-scale=1"> <link rel="stylesheet" href="style.css"> <title>Vue app</title> </head> <body> <div class="nav-bar"></div> <div id="app"> <div class="cart"> <p>Cart({{ cart }})</p> </div> <product :premium="premium" #add-to-cart="updateCart"></product> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="prior.js"></script> </body> </html>
Change This: <button :class="{ disabledButton: !inStock }" v-on:click="add-to-cart" :disabled="!inStock">Add to Cart</button> To be this: <button :class="{ disabledButton: !inStock }" v-on:click="addToCart" :disabled="!inStock">Add to Cart</button> So addToCart: and this function will emit add-to-cart event Also you can immediately run emmit onClick without adding function: <button :class="{ disabledButton: !inStock }" v-on:click="$emit('add-to-cart')" :disabled="!inStock">Add to Cart</button> Vue.component('product', { props: { premium: { type: Boolean, required: true } }, template: ` <div id="product"> <div class="product-image"> <img :src="image" /> </div> <div class="product-info"> <h1>{{ title }}</h1> <p>Shipping: {{ shipping }}</p> <p v-if="inStock">In Stock</p> <p v-else>Out of Stock</p> <h2>Details</h2> <ul> <li v-for="detail in details">{{ detail }}</li> </ul> <h3>Colors:</h3> <div v-for="(variant,index) in variants" :key="variant.variantId"> <div class="color-box" :style="{ backgroundColor: variant.variantColor }" #mouseover="updateProduct(index)"></div> </div> <button :class="{ disabledButton: !inStock }" v-on:click="addToCart" :disabled="!inStock">Add to Cart</button> </div> </div> `, data() { return { product: "Socks", brand: "Vue Mastery", selectedVariant: 0, details: ["80% cotton", "20% polyester", "Gender-neutral"], variants: [ { variantId: 2234, variantQuantity: 15, variantColor: "green", variantImage: "./assets/vmSocks-green.jpg" }, { variantId: 2235, variantQuantity: 0, variantColor: "blue", variantImage: "./assets/vmSocks-blue.jpg" } ] } }, methods: { addToCart() { this.$emit('add-to-cart') }, updateProduct(index) { this.selectedVariant = index } }, computed: { title() { return this.brand + ' ' + this.product }, image() { return this.variants[this.selectedVariant].variantImage }, inStock() { if (this.variants[this.selectedVariant].variantQuantity > 0) { return true } else { return false } }, shipping() { if (this.premium) { return "Free" } else { return 2.99 } } } }) var app = new Vue({ el: '#app', data: { premium: true, cart: 0 }, methods: { updateCart() { this.cart += 1 } } }) body { font-family: tahoma; color:#282828; margin: 0px; } .nav-bar { background: linear-gradient(-90deg, #84CF6A, #16C0B0); height: 60px; margin-bottom: 15px; } .product { display: flex; flex-flow: wrap; padding: 1rem; } img { border: 1px solid #d8d8d8; width: 70%; margin: 40px; box-shadow: 0px .5px 1px #d8d8d8; } .product-image { width: 80%; } .product-image, .product-info { margin-top: 10px; width: 50%; } .color-box { width: 40px; height: 40px; margin-top: 5px; } .cart { margin-right: 25px; float: right; border: 1px solid #d8d8d8; padding: 5px 20px; } button { margin-top: 30px; border: none; background-color: #1E95EA; color: white; height: 40px; width: 100px; font-size: 14px; } .disabledButton { background-color: #d8d8d8; } .review-form { width: 400px; padding: 20px; margin: 40px; border: 1px solid #d8d8d8; } input { width: 100%; height: 25px; margin-bottom: 20px; } textarea { width: 100%; height: 60px; } .tab { margin-left: 20px; cursor: pointer; } .activeTab { color: #16C0B0; text-decoration: underline; } <!DOCTYPE html> <html> <head> <meta name="viewpoint" content="width=devide-width, initial-scale=1"> <link rel="stylesheet" href="style.css"> <title>Vue app</title> </head> <body> <div class="nav-bar"></div> <div id="app"> <div class="cart"> <p>Cart({{ cart }})</p> </div> <product :premium="premium" #add-to-cart="updateCart"></product> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="prior.js"></script> </body> </html>