Display different maps with slider value mapbox - javascript

I have this code down below at the moment and I want to display the div id year 2018 differently based on which value the slider has. So to start the div id year is 2018 if value = 0 and then if value = 1 I want it to be 2019 and so on. Any ideas how to do it? Can I add it to the if statement by using the div based on which slider the if statement is on?
<body>
<style>
.map-overlay {
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
position: absolute;
width: 25%;
top: 0;
left: 0;
padding: 10px;
}
.map-overlay .map-overlay-inner {
background-color: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
border-radius: 3px;
padding: 10px;
margin-bottom: 10px;
}
.map-overlay h2 {
line-height: 24px;
display: block;
margin: 0 0 10px;
}
.map-overlay .legend .bar {
height: 10px;
width: 100%;
background: linear-gradient(to right, #fca107, #7f3121);
}
.map-overlay input {
background-color: transparent;
display: inline-block;
width: 100%;
position: relative;
margin: 0;
cursor: ew-resize;
}
</style>
<div id="map"></div>
<div class="map-overlay top">
<div class="map-overlay-inner">
<h2>Year</h2>
<div id="year">2018</div>
<input id="slider" type="range" min="0" max="3" step="1" value="0">
</div>
<div class="map-overlay-inner">
<div id="legend" class="legend">
<div class="bar"></div>
<div></div>
</div>
</div>
</div>
<script>
mapboxgl.accessToken = 'pk....';
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/user/cl38v9w2w000g14p8sd5cqqqp', // style URL
center: [-105.28461151261762, 40.005493336611714], // starting position [lng, lat]
zoom: 13 // starting zoom
});
map.on('load', () => {
slider.oninput = function() {
year.innerHTML = slider.value;
if (slider.value == 0) {
map.setStyle('mapbox://styles/user/cl38v9w2w000g14p8sd5cqqqp')
} else if (slider.value == 1) {
map.setStyle('mapbox://styles/mapbox/streets-v11')
} else if (slider.value == 2) {
map.setStyle('mapbox://styles/mapbox/outdoors-v11')
} else if (slider.value == 3) {
map.setStyle('mapbox://styles/mapbox/light-v10')
}
}
});
</script>
</body>

Just make sure your divs in .holder are in order.
I mean like this:
<div class="holder">
<div>2018</div>
<div>2019</div>
<div>2020</div>
<div>2021</div>
</div>
const slider = document.getElementById("slider");
const year = document.getElementById("year");
// function to make visible the selected value's div
const show = (i) =>
(document.querySelectorAll(".holder > div")[i].style.display = "block");
// makes visible the default selected value
// you can change defalut selected value in your html:
// <input id="slider" ... value="0" />
show(parseInt(slider.value));
slider.oninput = function() {
// makes all divs hidden each time the value changes
[...document.querySelectorAll(".holder > div")].forEach(
(i) => (i.style.display = "none")
);
const val = parseInt(slider.value);
// makes visible the selected value's div
show(val);
if (val == 0) {
year.innerHTML = "2018";
} else if (val === 1) {
year.innerHTML = "2019";
} else if (val === 2) {
year.innerHTML = "2020";
} else if (val === 3) {
year.innerHTML = "2021";
}
};
.map-overlay {
font: 12px/20px "Helvetica Neue", Arial, Helvetica, sans-serif;
position: absolute;
width: 25%;
top: 0;
left: 0;
padding: 10px;
}
.map-overlay .map-overlay-inner {
background-color: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
border-radius: 3px;
padding: 10px;
margin-bottom: 10px;
}
.map-overlay h2 {
line-height: 24px;
display: block;
margin: 0 0 10px;
}
.map-overlay .legend .bar {
height: 10px;
width: 100%;
background: linear-gradient(to right, #fca107, #7f3121);
}
.map-overlay input {
background-color: transparent;
display: inline-block;
width: 100%;
position: relative;
margin: 0;
cursor: ew-resize;
}
/* makes all divs hidden by default */
.holder>div {
display: none;
}
<div id="map"></div>
<div class="map-overlay top">
<div class="map-overlay-inner">
<h2>Year</h2>
<div id="year">2018</div>
<input id="slider" type="range" min="0" max="3" step="1" value="0" />
</div>
<div class="holder">
<div class="map-overlay-inner">
<div class="legend">
<h2>2018</h2>
<p>your content here 1</p>
</div>
</div>
<div class="map-overlay-inner">
<div class="legend">
<h2>2019</h2>
<p>your content here 2</p>
</div>
</div>
<div class="map-overlay-inner">
<div class="legend">
<h2>2020</h2>
<p>your content here 3</p>
</div>
</div>
<div class="map-overlay-inner">
<div class="legend">
<h2>2021</h2>
<p>your content here 4</p>
</div>
</div>
</div>
</div>

Related

ion-datetime dynamic value change doesn't work for certain weeks

This is a very strange problem to describe, but I'll try to do my best.
First of all, I'm working with vanilla JavaScript, I don't want to use Angular, React or anything like that because I don't know anything about them (although I wouldn't be against using jQuery if it was necessary).
What I'm trying to achieve
I'm trying to make a week selector using an ion-datetime element. I use this because it is the best option I could find to make a week selector while showing the whole calendar. If there is a less problematic way to do it, I'm open to hear it.
The way I do this is by listening to the ionChange event, detecting the clicked day, calculating the 7 days that belong to the same week and replacing calendar.value with the new array (see code below).
The problem
The thing is that when I click on certain weeks (it always happens in the same ones), an error pops up: TypeError: Cannot read properties of undefined (reading 'year'), but the process is always the same.
I add here a video of the problem in action: https://streamable.com/8toc8g
Code
#import url('https://fonts.googleapis.com/css2?family=Lilita+One&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght#700&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Indie+Flower&display=swap');
:root {
--bg-rosa: #f3e1e3;
--top1-rosa: #fbb6ad;
--top2-rosa: #b4dadf;
--top1-rosa-aux: #facec8;
--top2-rosa-aux: #d5e7e8;
--bg-turquesa: #d5e7e8;
--top1-turquesa: #6ccac8;
--top2-turquesa: #efb049;
--top1-turquesa-aux: #8fd9d8;
--top2-turquesa-aux: #f0cb90;
--bg-amarillo: #fffdeb;
--top1-amarillo: #ffe373;
--top2-amarillo: #ffabab;
--top1-amarillo-aux: #fff0b3;
--top2-amarillo-aux: #ffc7c7;
--bg-morado: #ece4ff;
--top1-morado: #a4a4eb;
--top2-morado: #a1dae6;
--top1-morado-aux: #c2c2f2;
--top2-morado-aux: #c7ebf2;
--bg: var(--bg-morado);
--top1: var(--top1-morado);
--top1-aux: var(--top1-morado-aux);
--top2: var(--top2-morado);
--top2-aux: var(--top2-morado-aux);
--top-text: #444c53;
}
body {
position: relative;
background: var(--bg);
padding: 0;
margin: 0;
}
.week {
display: grid;
grid-template-columns: repeat(7, minmax(10em, 25em));
width: 100%;
height: 100%;
padding: 1em;
}
.day {
position: relative;
flex-grow: 1;
height: 100%;
}
.day::after {
content: "";
display: block;
width: 100%;
height: 100%;
background: var(--bg);
opacity: 0;
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
.day:hover::after {
opacity: 0.2;
}
.top {
display: flex;
align-items:center;
justify-content:center;
padding: 0.35em;
font-family: 'Lilita One', cursive;
font-size: min(calc(1em + 1vw), calc(1em + 2vh));
color: var(--top-text);
text-align: center;
vertical-align: baseline;
border-radius: calc(1em + 1vh) calc(1em + 1vh) 0 0;
}
.content {
border-radius: 0 0 calc(1em + 1vh) calc(1em + 1vh);
}
.info {
/* height: 49vh; */
height: calc(49vh - 0.4vw);
font-family: 'Indie Flower', cursive;
font-weight: 500;
font-size: 1.2rem;
padding: 0.5rem 0.5rem 0 1rem;
overflow-y: scroll;
background-color: #ffffff;
background-size: 1.5rem 1.5rem;
background-image: repeating-linear-gradient(0deg, #d7d7d780, #d7d7d780 1px, #ffffff 1px, #ffffff);
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track-piece:end {
background: transparent;
margin-bottom: 1.5vh;
}
::-webkit-scrollbar-thumb {
border-radius: 8px;
background: #c2c9d2;
}
.frame {
padding: 0 0.25em 0.25em 0.25em;
height: calc(100% - min(calc(1em + 1vw), calc(1em + 2vh)) - 2em);
}
.frame-square {
background-color: var(--top1);
}
.frame-dotted {
background-color: var(--top2);
}
.square {
background-position: center;
background-color: var(--top1);
background-image: linear-gradient(var(--top1-aux) 2px, transparent 2px), linear-gradient(90deg, var(--top1-aux) 2px, transparent 2px);
background-size: 1em 0.9em, 1em 0.9em;
}
.dotted {
background-position: center;
background-color: var(--top2);
background: radial-gradient(circle, transparent 20%, var(--top2) 20%, var(--top2) 80%, transparent 80%, transparent), radial-gradient(circle, transparent 20%, var(--top2) 20%, var(--top2) 80%, transparent 80%, transparent) 17.5px 17.5px, linear-gradient(var(--top2-aux) 1.4px, transparent 1.4px) 0 -0.7px, linear-gradient(90deg, var(--top2-aux) 1.4px, var(--top2-aux) 1.4px) -0.7px 0;
background-size: 35px 35px, 35px 35px, 17.5px 17.5px, 17.5px 17.5px;
}
#calendario {
width: 30vw;
height: 40vh;
margin: 0;
margin-left: 1em;
margin-bottom: 1em;
border-style: solid;
border-color: var(--top1);
border-radius: 1em;
}
.ion-color-same {
--ion-color-base: var(--top1);
--ion-color-contrast: white;
}
ion-datetime {
--background: var(--bg);
border-radius: 16px;
margin-right: 5em;
}
table {
height: 100%;
width: 100%;
}
#inf {
padding: 0;
margin: 0;
height: 15rem;
}
#frase {
margin: 3rem;
font-family: 'Dancing Script', 'Lilita One', cursive;
color: var(--top-text);
}
#frase-container {
width: 100%;
height: 100%;
text-align: center;
}
#fondo-frase {
display: flex;
height: calc(100% - 1em);
width: calc(100% - 2em);
max-height: calc(100% - 1em);
max-width: calc(100% - 2em);
margin: 1em;
margin-top: 0;
align-items:center;
justify-content:center;
}
ion-datetime::part(datetime-year){
background: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<script type="module" src="https://cdn.jsdelivr.net/npm/#ionic/core/dist/ionic/ionic.esm.js"></script>
<script nomodule src="https://cdn.jsdelivr.net/npm/#ionic/core/dist/ionic/ionic.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#ionic/core/css/ionic.bundle.css" />
<link rel="stylesheet" href="style.css">
<script>
function valueChanged() {
const calendario = document.getElementById('calendario');
if (calendario.value.length != 7) {
const last = calendario.value[calendario.value.length - 1];
let date = new Date(last);
date = getMonday(date);
selectFromMonday(date);
}
}
function getMonday(date) {
switch (date.getDay()) {
case 2:
date.setDate(date.getDate() - 1);
break;
case 3:
date.setDate(date.getDate() - 2);
break;
case 4:
date.setDate(date.getDate() - 3);
break;
case 5:
date.setDate(date.getDate() - 4);
break;
case 6:
date.setDate(date.getDate() - 5);
break;
case 0:
date.setDate(date.getDate() - 6);
break;
}
return date;
}
async function selectFromMonday(date) {
let calendario = document.getElementById('calendario');
let diaIds = ['lunes', 'martes', 'miercoles', 'jueves', 'viernes', 'sabado', 'domingo'];
let value = [];
for (let i = 0; i < 7; i++) {
const dia = document.getElementById(diaIds[i]);
value.push(date.getFullYear() + "-" + parseInt(date.getMonth()+1) + "-" + date.getDate());
dia.getElementsByClassName('fecha')[0].value = value[value.length - 1];
dia.getElementsByClassName('content info')[0].innerHTML = "";
date.setDate(date.getDate() + 1);
}
calendario.value = value;
}
</script>
</head>
<body>
<table id="tabla">
<tr id="sup"><td>
<div class="week">
<div class="day" id="lunes">
<input type="hidden" class="fecha">
<div class="top square">LUNES</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
<div class="day" id="martes">
<input type="hidden" class="fecha">
<div class="top dotted">MARTES</div>
<div class="content frame frame-dotted">
<div class="content info"></div>
</div>
</div>
<div class="day" id="miercoles">
<input type="hidden" class="fecha">
<div class="top square">MIÉRCOLES</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
<div class="day" id="jueves">
<input type="hidden" class="fecha">
<div class="top dotted">JUEVES</div>
<div class="content frame frame-dotted">
<div class="content info"></div>
</div>
</div>
<div class="day" id="viernes">
<input type="hidden" class="fecha">
<div class="top square">VIERNES</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
<div class="day" id="sabado">
<input type="hidden" class="fecha">
<div class="top dotted">SÁBADO</div>
<div class="content frame frame-dotted">
<div class="content info"></div>
</div>
</div>
<div class="day" id="domingo">
<input type="hidden" class="fecha">
<div class="top square">DOMINGO</div>
<div class="content frame frame-square">
<div class="content info"></div>
</div>
</div>
</div>
</td></tr>
<tr><td id="inf">
<table><tr><td>
<ion-datetime id="calendario"
presentation="date"
locale="es-ES"
first-day-of-week="1"
min="1970-01-01T00:00:00"
max="2200-12-31T23:59:59"
size="cover"
color="same"
multiple="true">
</ion-datetime>
</td><td id="frase-container">
<div id="fondo-frase">
<h1 id="frase"></h1>
</div>
</td></tr></table>
</td>
</tr>
</table>
<script>
let today = new Date();
//today.setTime( today.getTime() - today.getTimezoneOffset() * 60 * 1000 );
let monday = getMonday(today);
selectFromMonday(monday);
let calen = document.getElementById('calendario');
calen.addEventListener('ionChange', function () {
valueChanged()
});
</script>
</body>
</html>
Okay, I finally found the problem. I initially used the Date.toISOString() method and splitted the result to get just the date, but since it gave me a date outside my timezone I had to do it manually.
So the thing is that when I used my own method, I did not take into account that for 1 digit days (or months) it adds a zero before so that it's 2 digits. For example, for October 3 2022 I got 2022-10-3 with my method and 2022-10-03 with the other one, and that was what caused the problems.

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>

How To Reload The Web Page Using A Button In JavaScript

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 ! :)

How to print out dynamic items from array to the DOM

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);

Loop through Rounds while calling for New user Selection after each round Javascript

I am working on a Rock Paper Scissors game, and I am stuck on a for concepts. I want the user to select the amount of rounds they want through a textbox. Each time the user clicks on a specific image (rock, paper, or scissors) the computer will randomly compile and this will select and image for the computer. Both user and computer chosen images will display in the center of the page in the red and blue squares. I want this to run in a loop until all rounds are complete and then decide an ultimate winner. I am getting lost on how I will make my Loop call for the function where I am having the user select an image, and do this until cpu or user wins. All I am looking for is a bit of guidance as to why I can't figure out how to call for the users selection and then chose a user selection, and repeat this process to completion.
function startGame() {
document.getElementById("gameInfo").style.display = "contents";
}
function clearGame() {
document.getElementById("gameInfo").style.display = "none";
document.getElementById("cpu").src = "";
document.getElementById("user").src = "";
document.getElementById("winner").innerHTML = "";
document.getElementById("userDisplay").innerHTML = "";
document.getElementById("userName").value = "";
}
function displayName() {
var txtName = document.getElementById("userName").value;
document.getElementById("userDisplay").innerHTML = txtName;
}
/*function roundNumber(input) {
var total = document.getElementById("roundChoice").value;
//compSelection(total.value);
console.log(total);
}*/
function userPick(input) {
document.getElementById("user").src = input.src;
roundNumber(input.id);
console.log(input.id);
}
function roundNumber(uInput) {
var total;
var element = document.getElementById("roundChoice").value;
if (element != null) {
total = element.value;
document.getElementById("roundChoice").value = "Let's Begin";
} else {
document.getElementById("roundChoice").value = "Enter Rounds!!!";
}
for (var i = 0; i <= total; i++) {
var compSelect = Math.floor(Math.random() * 3 + 1);
var winner = document.getElementById("winner");
if (compSelect === 1) {
document.getElementById("cpu").src = "images/rock.jpg";
if (uInput === "rock_1") {
winner.innerHTML = "you tied!"
i--;
} else if (uInput === "paper_1") {
winner.innerHTML = "User Wins Round" + i + "!"
} else {
winner.innerHTML = "Computer Wins Round" + i + "!"
}
} else if (compSelect === 2) {
document.getElementById("cpu").src = "images/paper.jpg";
if (uInput === "paper_1") {
winner.innerHTML = "You tied!"
i--;
} else if (uInput === "scissors_1") {
winner.innerHTML("User Wins Round" + i + "!")
} else {
winner.innerHTML = "Computer Wins Round" + i + "!"
}
} else {
document.getElementById("cpu").src = "images/scissors.jpg";
if (uInput === "scissors_1") {
winner.innerHTML = "You tied!"
i--;
} else if (uInput === "rock_1") {
winner.innerHTML = "User Wins Round" + i + "!"
} else {
winner.innerHTML = "computer WIns"
}
}
}
}
body {
font: 80% arial, helvetica, sans-serif;
background: black;
margin: 0;
}
#container {
position: relative;
width: 1100px;
border: solid orange;
border-width: 0 3px;
margin: auto;
overflow: hidden;
height: 78em;
}
#header {
padding: 1em;
position: relative;
overflow: hidden;
}
#title {
color: white;
text-align: center;
font: 280% courier;
text-decoration: none;
text-shadow: 1px 1px 8px orange;
}
p.instruct {
background: grey;
color: white;
text-align: center;
font-size: 120%;
position: relative;
border: solid orange;
border-width: 1px;
padding: .5em 0 .5em 0;
}
#startButton {
float: left;
margin: 0 0 2em 2em;
}
#button {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#clearButton {
margin: 0 0 0 12em;
}
#newButton {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#modifiedGame {
float: right;
margin: 0 2em 2em 0;
}
#newGameBtn {
background: black;
border: dotted red;
color: red;
padding: 4px;
}
#nameInput {
text-align: center;
margin: 3em 0 1em 0;
}
#userName {
text-align: center;
background: black;
border: dotted orange;
padding: 4px;
}
#submitName {
margin: 0 0 5em 39em;
}
#rounds {
clear: both;
text-align: center;
margin: 0;
}
#roundChoice {
text-align: center;
padding: 4px;
border: dotted orange;
background: black;
}
#enterRounds {
margin: 1em 0 2em 39.5em;
}
p.winner {
background: grey;
color: white;
/*clear: both;*/
}
::placeholder {
color: orange;
}
input,
select,
textarea {
color: orange;
}
#images,
p {
clear: both;
color: white;
}
#images {
float: left;
}
#images2 {
float: right;
}
#cpuNameTag {
text-align: center;
color: white;
margin: 0 0 0 45em;
}
#cpuNameTag2 {
color: white;
float: left;
}
#paper_1 {
width: 80px;
height: 80px;
}
#paper_2 {
width: 80px;
height: 80px;
}
#rock_1 {
width: 80px;
height: 80px;
}
#rock_2 {
width: 80px;
height: 80px;
}
#scissors_1 {
width: 80px;
height: 80px;
}
#scissors_2 {
width: 80px;
height: 80px;
}
#rock {
float: left;
}
#paper {
float: left;
}
#scissors {
float: left;
}
#rock2 {
float: right;
}
#scissors2 {
float: right;
}
#paper2 {
float: right;
}
#user_displayed_choice {
background-color: red;
width: 150px;
height: 150px;
float: right;
}
#cpu_displayed_choice {
clear: both;
background-color: blue;
width: 150px;
height: 150px;
float: right;
}
#displayed_choices {
margin: 0 31em 0 0;
}
#user {
width: 100px;
height: 100px;
}
#cpu {
width: 100px;
height: 100px;
}
#gameInfo {
display: none;
}
h4 {
color: orange;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CSS intro" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<title>Rock Paper Scissors</title>
<link href="rps.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="rps.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1 id="title"><b>Welcome </b><br><b>to</b> <br><b>Rock Paper Scissors!</b></h1>
</div>
<!--Instructions for game-->
<p class="instruct">Ready to attempt a game of Rock, Paper, Scissors? Select the start button, and then choose the amount of rounds you want to play. Ties in each round will not count towards total rounds. If a tie is present at the end of all the rounds, one final overtime
round will decide the winner. If you dare, try our harder version by beating the computer to unlock.</p>
<!--Buttons for Start, Clear, and Harder Game-->
<div id="modifiedGame">
<input type="button" id="newGameBtn" onclick="newGame" value="Want to try a harder game?">
</div>
<div id="startButton">
<input type="button" id="button" onclick="startGame()" value="Start Game">
</div>
<section id="gameInfo">
<div id="clearButton">
<input type="button" id="newButton" onclick="clearGame()" value="Clear Game">
</div>
<!--^^^-->
<!--Name Input, Round Input-->
<div id="nameInput">
<input type="text" id="userName" placeholder="What is your name?" autofocus required>
</div>
<div id="submitName">
<input type="button" id="nameButton" value="Secure Name" onclick="displayName(this)">
</div>
<div id="rounds">
<input type="text" id="roundChoice" placeholder="Enter # of Rounds" autofocus required>
</div>
<div id="enterRounds">
<input type="button" id="roundButton" value="Set Rounds" onclick="roundNumber(this)">
</div>
<div id="cpuNameTag2">
<h4 id="userDisplay" value=""></h4>
</div>
<div id="cpuNameTag">
<h4>CPU Chooses:</h4>
</div>
<!--Clickable Images for User to Choose. Some Displayed by CPU name to show what CPU Chose after User-->
<div id="images">
<div id="rock">
<img src="images/rock.jpg" alt="rock" id="rock_1" onclick="userPick(this)">
</div>
<div id="paper">
<img src="images/paper.jpg" alt="paper" id="paper_1" onclick="userPick(this)">
</div>
<div id="scissors">
<img src="images/scissors.jpg" alt="scissors" id="scissors_1" onclick="userPick(this)">
</div>
</div>
<div id="images2">
<div id="scissors2">
<img src="images/scissors.jpg" alt="scissors" id="scissors_2">
</div>
<div id="paper2">
<img src="images/paper.jpg" alt="paper" id="paper_2">
</div>
<div id="rock2">
<img src="images/rock.jpg" alt="rock" id="rock_2">
</div>
</div>
<div id="displayed_choices">
<div id="cpu_displayed_choice">
<img id="cpu" src="">
</div>
<div id="user_displayed_choice">
<img id="user" src="">
</div>
</div>
<h1 id="winner"></h1>
</section>
</div>
</body>
</html>
Here you have a working example without the for loop, using 3 global variables (currentRound, totalRounds and wins).
var currentRound = -1;
var totalRounds = -1;
var wins = -1;
function startGame() {
document.getElementById("gameInfo").style.display = "contents";
}
function clearGame() {
document.getElementById("gameInfo").style.display = "none";
document.getElementById("cpu").src = "";
document.getElementById("user").src = "";
document.getElementById("winner").innerHTML = "";
document.getElementById("userDisplay").innerHTML = "";
document.getElementById("userName").value = "";
}
function displayName() {
var txtName = document.getElementById("userName").value;
document.getElementById("userDisplay").innerHTML = txtName;
}
function setRounds() {
var value = document.getElementById("roundChoice").value;
if (value) {
totalRounds = parseInt(value);
currentRound = 0;
wins = 0;
document.getElementById("winner").innerHTML = "Let's Begin";
} else {
document.getElementById("roundChoice").value = "Enter Rounds!!!";
totalRounds = -1;
}
}
function userPick(input) {
if (totalRounds < 0) {
alert("Enter Rounds!!!");
return;
}
if (currentRound >= totalRounds) {
alert("Rounds Finished! Enter Rounds again!!!");
return;
}
//console.log(currentRound + "," + totalRounds)
document.getElementById("user").src = input.src;
currentRound++;
roundNumber(input.id);
}
function roundNumber(uInput) {
var compSelect = Math.floor(Math.random() * 3 + 1);
var winner = document.getElementById("winner");
var i = currentRound + 1;
if (compSelect === 1) {
document.getElementById("cpu").src = "https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg";
if (uInput === "rock_1") {
winner.innerHTML = "you tied!"
currentRound--;
} else if (uInput === "paper_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "Computer Wins Round " + i + "!"
}
} else if (compSelect === 2) {
document.getElementById("cpu").src = "https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png";
if (uInput === "paper_1") {
winner.innerHTML = "You tied!"
currentRound--;
} else if (uInput === "scissors_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "Computer Wins Round " + i + "!"
}
} else {
document.getElementById("cpu").src = "https://image.flaticon.com/icons/png/128/164/164986.png";
if (uInput === "scissors_1") {
winner.innerHTML = "You tied!"
currentRound--;
} else if (uInput === "rock_1") {
wins++;
winner.innerHTML = "User Wins Round " + i + "!"
} else {
winner.innerHTML = "computer WIn " + i + "!"
}
}
if (currentRound == totalRounds) {
alert(totalRounds + " Finished:\n"
+ "- wins: " + wins + "\n"
+ "- looses: " + (totalRounds - wins))
}
}
body {
font: 80% arial, helvetica, sans-serif;
background: black;
margin: 0;
}
input[type=button],
#images img {
cursor: pointer;
}
#container {
position: relative;
width: 1100px;
border: solid orange;
border-width: 0 3px;
margin: auto;
overflow: hidden;
height: 78em;
}
#header {
padding: 1em;
position: relative;
overflow: hidden;
}
#title {
color: white;
text-align: center;
font: 280% courier;
text-decoration: none;
text-shadow: 1px 1px 8px orange;
}
p.instruct {
background: grey;
color: white;
text-align: center;
font-size: 120%;
position: relative;
border: solid orange;
border-width: 1px;
padding: .5em 0 .5em 0;
}
#startButton {
float: left;
margin: 0 0 2em 2em;
}
#button {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#clearButton {
margin: 0 0 0 12em;
}
#newButton {
background: black;
border: dotted orange;
color: orange;
padding: 4px;
}
#modifiedGame {
float: right;
margin: 0 2em 2em 0;
}
#newGameBtn {
background: black;
border: dotted red;
color: red;
padding: 4px;
}
#nameInput {
text-align: center;
margin: 3em 0 1em 0;
}
#userName {
text-align: center;
background: black;
border: dotted orange;
padding: 4px;
}
#submitName {
margin: 0 0 5em 39em;
}
#rounds {
clear: both;
text-align: center;
margin: 0;
}
#roundChoice {
text-align: center;
padding: 4px;
border: dotted orange;
background: black;
}
#enterRounds {
margin: 1em 0 2em 39.5em;
}
p.winner {
background: grey;
color: white;
/*clear: both;*/
}
::placeholder {
color: orange;
}
input,
select,
textarea {
color: orange;
}
#images,
p {
clear: both;
color: white;
float: left;
}
#images2 {
float: right;
}
#cpuNameTag {
text-align: center;
color: white;
margin: 0 0 0 45em;
}
#cpuNameTag2 {
color: white;
float: left;
}
#paper_1 {
width: 80px;
height: 80px;
}
#paper_2 {
width: 80px;
height: 80px;
}
#rock_1 {
width: 80px;
height: 80px;
}
#rock_2 {
width: 80px;
height: 80px;
}
#scissors_1 {
width: 80px;
height: 80px;
}
#scissors_2 {
width: 80px;
height: 80px;
}
#rock {
float: left;
}
#paper {
float: left;
}
#scissors {
float: left;
}
#rock2 {
float: right;
}
#scissors2 {
float: right;
}
#paper2 {
float: right;
}
#user_displayed_choice {
background-color: red;
width: 150px;
height: 150px;
float: right;
}
#cpu_displayed_choice {
clear: both;
background-color: blue;
width: 150px;
height: 150px;
float: right;
}
#displayed_choices {
margin: 0 31em 0 0;
}
#user {
width: 100px;
height: 100px;
}
#cpu {
width: 100px;
height: 100px;
}
#gameInfo {
display: none;
}
h4 {
color: orange;
}
#winner {
text-align: center;
color: white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="CSS intro" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<title>Rock Paper Scissors</title>
<link href="rps.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="rps.js"></script>
</head>
<body>
<div id="container">
<div id="header">
<h1 id="title"><b>Welcome </b><br><b>to</b> <br><b>Rock Paper Scissors!</b></h1>
</div>
<!--Instructions for game-->
<p class="instruct">Ready to attempt a game of Rock, Paper, Scissors? Select the start button, and then choose the amount of rounds you want to play. Ties in each round will not count towards total rounds. If a tie is present at the end of all the rounds, one final overtime
round will decide the winner. If you dare, try our harder version by beating the computer to unlock.</p>
<!--Buttons for Start, Clear, and Harder Game-->
<div id="modifiedGame">
<input type="button" id="newGameBtn" onclick="newGame" value="Want to try a harder game?">
</div>
<div id="startButton">
<input type="button" id="button" onclick="startGame()" value="Start Game">
</div>
<section id="gameInfo">
<div id="clearButton">
<input type="button" id="newButton" onclick="clearGame()" value="Clear Game">
</div>
<!--^^^-->
<!--Name Input, Round Input-->
<div id="nameInput">
<input type="text" id="userName" placeholder="What is your name?" autofocus required>
</div>
<div id="submitName">
<input type="button" id="nameButton" value="Secure Name" onclick="displayName(this)">
</div>
<div id="rounds">
<input type="text" id="roundChoice" placeholder="Enter # of Rounds" autofocus required>
</div>
<div id="enterRounds">
<input type="button" id="roundButton" value="Set Rounds" onclick="setRounds()">
</div>
<div id="cpuNameTag2">
<h4 id="userDisplay" value=""></h4>
</div>
<div id="cpuNameTag">
<h4>CPU Chooses:</h4>
</div>
<!--Clickable Images for User to Choose. Some Displayed by CPU name to show what CPU Chose after User-->
<div id="images">
<div id="rock">
<img src="https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg" alt="rock" id="rock_1" onclick="userPick(this)">
</div>
<div id="paper">
<img src="https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png" alt="paper" id="paper_1" onclick="userPick(this)">
</div>
<div id="scissors">
<img src="https://image.flaticon.com/icons/png/128/164/164986.png" alt="scissors" id="scissors_1" onclick="userPick(this)">
</div>
</div>
<div id="images2">
<div id="scissors2">
<img src="https://image.flaticon.com/icons/png/128/164/164986.png" alt="scissors" id="scissors_2">
</div>
<div id="paper2">
<img src="https://i.pinimg.com/originals/7c/58/78/7c58781da79c7e9b089f206a1ad7b9b5.png" alt="paper" id="paper_2">
</div>
<div id="rock2">
<img src="https://image.freepik.com/iconos-gratis/rock-n-roll-gesto-simbolo-de-la-mano-esbozado_318-72191.jpg" alt="rock" id="rock_2">
</div>
</div>
<div id="displayed_choices">
<div id="cpu_displayed_choice">
<img id="cpu" src="">
</div>
<div id="user_displayed_choice">
<img id="user" src="">
</div>
</div>
<h1 id="winner"></h1>
</section>
</div>
</body>
</html>

Categories

Resources