Assign TWO Images to Radio Button - javascript

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>

Related

<template> clone but with texts from user input

I am trying to create a comment section for my page, I used the template element to create the box and format for my user's pic and name but i'm having difficulties adding the text received from the user to get into the box. right now it creates the box and just puts the text outside/under it. How can I create a element to store inside the template?
function postComment() {
//Clone new box for comment
var temp = document.getElementsByTagName("template")[0];
var clone = temp.content.cloneNode(true);
var newComment = document.getElementById("new-comment");
newComment.appendChild(clone)
//Get comment
var userComment = document.getElementById("comment-box").value;
var text = document.createElement('p');
text.innerHTML = userComment;
newComment.appendChild(text)
//reset the comment box
document.getElementById("comment-box").value = "";
}
var post = document.getElementById("post");
post.addEventListener("click", function(e) {
e.preventDefault();
postComment()
})
.comment-box,
.post-comment .list {
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 2px black;
}
.comment-section {
width: 100%;
height: auto;
margin: 0 auto;
}
.post-comment .list {
width: 100%;
margin-bottom: 12px;
}
.post-comment .list .user {
display: flex;
padding: 8px;
overflow: hidden;
}
.post-comment .list .user img {
height: 38px;
width: 38px;
margin-right: 10px;
border-radius: 50%;
}
.comment-section .name {
text-transform: uppercase;
}
.post-comment .list .day {
font-size: 12px;
}
.post-comment {
padding: 0 0 15px 58px
}
#comment-box {
border: none;
border-radius: 5px;
}
.comment-box .user {
display: flex;
width: min-content;
}
.comment-box .image img {
width: 24px;
height: 24px;
margin-right: 10px;
border-radius: 50%;
}
<div class="row">
<div class="comment-section">
<div class="post-comment">
<div class="list">
<div class="user">
<div class="user-image"><img src="./images/ok.webp"></div>
<div class="user-name">
<div class="name">TOM</div>
<div class="day">100 days ago</div>
</div>
</div>
<div class="comment">LOREM IPSUN DABUN VUB</div>
</div>
<template>
<div class="list">
<div class="user">
<div class="user-image"><img src="./images/Animal-Crossing-Tom-Nook-with-Money.jpg"></div>
<div class="user-name">
<div class="name">Tom Nook</div>
<div class="day">1 second ago</div>
</div>
</div>
</div>
</template>
<div id="new-comment"></div>
<div class="comment-box">
<div class="user">
<div class="user-image"><img src="./images/OK.webp"></div>
<form>
<textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
<button id="post">Comment</button>
</form>
</div>
</div>
</div>
</div>
</div>
Try this and see if this suits your requirements:
function postComment() {
//Get comment
var userComment = document.getElementById("comment-box").value;
var html = '<div class="list">' +
'<div class="user">' +
'<div class="user-image"><img src="./images/Animal-Crossing-Tom-Nook-with-Money.jpg"></div>' +
'<div class="user-name">' +
'<div class="name">Tom Nook</div>' +
'<div class="day">1 second ago</div>' +
'</div>' +
'</div>' +
'<div id="new-comment">' + userComment + '</div>' +
'</div>';
var template = document.getElementsByTagName("template")[0];
template.insertAdjacentHTML("afterend", html);
//reset the comment box
document.getElementById("comment-box").value = "";
}
var post = document.getElementById("post");
post.addEventListener("click", function(e) {
e.preventDefault();
postComment()
})
.comment-box,
.post-comment .list {
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 2px black;
}
.comment-section {
width: 100%;
height: auto;
margin: 0 auto;
}
.post-comment .list {
width: 100%;
margin-bottom: 12px;
}
.post-comment .list .user {
display: flex;
padding: 8px;
overflow: hidden;
}
.post-comment .list .user img {
height: 38px;
width: 38px;
margin-right: 10px;
border-radius: 50%;
}
.comment-section .name {
text-transform: uppercase;
}
<div class="row">
<div class="comment-section">
<div class="post-comment">
<div class="list">
<div class="user">
<div class="user-image"><img src="./images/ok.webp"></div>
<div class="user-name">
<div class="name">TOM</div>
<div class="day">100 days ago</div>
</div>
</div>
<div class="comment">LOREM IPSUN DABUN VUB</div>
</div>
<template></template>
<div class="comment-box">
<div class="user">
<div class="user-image"><img src="./images/OK.webp"></div>
<form>
<textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
<button id="post">Comment</button>
</form>
</div>
</div>
</div>
</div>
</div>

Display different maps with slider value mapbox

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>

Add Javascript counters to colour counter

I am making a colour counter application, That has has 6 different colours.
I am currently trying to implement a pure JavaScript counter that has a individual counter for each colour.
(Correction: It is not to count the different colours displayed on the page, but when the user sees a colour in their surrounding environment that matches one of the 6 colours, they increase the counter by 1, for example the user sees the sky is blue and the grass is green, The user hovers over the blue colour, the increase and decrease buttons appear, the user increases the blue colour by 1 increment, Then for the grass the user hovers over the green colour, again the button appears and the user increases the green counter by 1.)
When a user hovers over the colour buttons must appear to increase or decrease the counter by 1, to a minimum of 0.
The count of each colour must always be displayed above the colour.
My current method seems rather long I'm sure there is a way to set up some sort of a method to handle all colours but again to have separate counters for each colour.
Please see the below image for what I am trying to achieve:
See this image
Any help would be appreciated,
I have included my current code below for reference
var green = 0;
var countEl1 = document.getElementById("green");
function plus1(){
green++;
countEl1.value = green;
}
function minus1(){
if (green > 0) {
green--;
countEl1.value = green;
}
}
var brown = 0;
var countEl2 = document.getElementById("brown");
function plus2(){
brown++;
countEl2.value = brown;
}
function minus2(){
if (brown > 0) {
brown--;
countEl2.value = brown;
}
}
var blue = 0;
var countEl3 = document.getElementById("blue");
function plus3(){
blue++;
countEl3.value = blue;
}
function minus3(){
if (blue > 0) {
blue--;
countEl3.value = blue;
}
}
var yellow = 0;
var countEl4 = document.getElementById("yellow");
function plus4(){
yellow++;
countEl4.value = yellow;
}
function minus4(){
if (yellow > 0) {
yellow--;
countEl4.value = yellow;
}
}
var gold = 0;
var countEl5 = document.getElementById("gold");
function plus5(){
gold++;
countEl5.value = gold;
}
function minus5(){
if (gold > 0) {
gold--;
countEl5.value = gold;
}
}
var red = 0;
var countEl6 = document.getElementById("red");
function plus6(){
red++;
countEl6.value = red;
}
function minus6(){
if (red > 0) {
red--;
countEl6.value = red;
}
}
.pyramid {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
width: 100vmin;
aspect-ratio: 9 / 15; /* 2/1 */
background-color: white;
display: grid;
grid-template-columns: 1fr;
}
.pyramid > * {
background: white;
}
.one {
background-color: rgba(234, 27, 7, 0.97);
}
.two {
background-color: rgba(244, 182, 0, 0.98);
margin-top: 10px;
}
.three {
background-color: rgba(249, 224, 41, 0.98);
margin-top: 10px;
}
.four {
background-color: rgba(4, 157, 252, 0.98);
}
.five {
background-color: rgba(167, 118, 67, 0.99);
gap: 0% !important;
}
.six {
background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
display: inline-block;
width: 20px;
background-color: transparent;
outline: none;
border: none;
text-align: center;
cursor: pointer;
padding: 0px;
color: black;
height: 33px;
font-family: 'Open Sans';
}
#container {
width: 100px;
height: 100px;
position: relative;
}
#navi,
#infoi {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
#infoi {
z-index: 10;
}
button {
border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Colour counter</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/Main.js"></script>
</head>
<body>
<div id="container">
<h1>Colour counter</h1>
<div class="pyramid">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
</div>
<h1>Counter Test</h1>
<div id="input_div">
<input type="button" value="-" id="minus1" onclick="minus1()">
<input type="text" size="25" value="0" id="green">
<input type="button" value="+" id="plus1" onclick="plus1()">
<script src="js/Main.js"></script>
</div>
<div id="input_div2">
<input type="button" value="-" id="minus2" onclick="minus2()">
<input type="text" size="25" value="0" id="brown">
<input type="button" value="+" id="plus2" onclick="plus2()">
<script src="js/Main.js"></script>
</div>
</div>
</body>
</html>
Use an array from which do the operations on the DOM and apply map to do each colour's job, which would be to programatically attach the event listener to the DOM elements. Also, ensure the DOM has fully loaded before running your JS code:
window.onload = function() {
let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
.map(id => {
let colour = {
elementCount: document.getElementById(id),
elementPlus: document.getElementById(`${id}_plus`),
elementMinus: document.getElementById(`${id}_minus`),
counter: 0,
};
colour.elementPlus.addEventListener("click", function() {
colour.counter++;
colour.elementCount.value = colour.counter;
});
colour.elementMinus.addEventListener("click", function() {
if (colour.counter > 0) {
colour.counter--;
colour.elementCount.value = colour.counter;
}
});
return colour;
});
};
Adapt the HTML so the IDs match the ones used in the JS:
Instead of minus1, use green_minus. Do the same for the rest of minus buttons.
Instead of plus1, use green_minus. Do the same for the rest of plus buttons.
Adapt the HTML removing the onClick attribute (it is now assigned programatically using JS).
As a plus, now you have the colours variable, where all the DOM elements and each colour counter are stored for further inspection and or modification.
As an example, one colour in the HTML would be like:
<div id="input_div">
<input type="button" value="-" id="green_minus">
<input type="text" size="25" value="0" id="green">
<input type="button" value="+" id="green_plus">
</div>
<!-- Other colours... -->
<script src="js/Main.js"></script>
window.onload = function() {
let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
.map(id => {
let colour = {
elementCount: document.getElementById(id),
elementPlus: document.getElementById(`${id}_plus`),
elementMinus: document.getElementById(`${id}_minus`),
counter: 0,
};
colour.elementPlus.addEventListener("click", function() {
colour.counter++;
colour.elementCount.value = colour.counter;
});
colour.elementMinus.addEventListener("click", function() {
if (colour.counter > 0) {
colour.counter--;
colour.elementCount.value = colour.counter;
}
});
return colour;
});
};
.pyramid {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
width: 100vmin;
aspect-ratio: 9 / 15; /* 2/1 */
background-color: white;
display: grid;
grid-template-columns: 1fr;
}
.pyramid > * {
background: white;
}
.one {
background-color: rgba(234, 27, 7, 0.97);
}
.two {
background-color: rgba(244, 182, 0, 0.98);
margin-top: 10px;
}
.three {
background-color: rgba(249, 224, 41, 0.98);
margin-top: 10px;
}
.four {
background-color: rgba(4, 157, 252, 0.98);
}
.five {
background-color: rgba(167, 118, 67, 0.99);
gap: 0% !important;
}
.six {
background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
display: inline-block;
width: 20px;
background-color: transparent;
outline: none;
border: none;
text-align: center;
cursor: pointer;
padding: 0px;
color: black;
height: 33px;
font-family: 'Open Sans';
}
#container {
width: 100px;
height: 100px;
position: relative;
}
#navi,
#infoi {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
#infoi {
z-index: 10;
}
button {
border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Colour counter</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/Main.js"></script>
</head>
<body>
<div id="container">
<h1>Colour counter</h1>
<div class="pyramid">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
</div>
<h1>Counter Test</h1>
<div id="input_div">
<input type="button" value="-" id="green_minus">
<input type="text" size="25" value="0" id="green">
<input type="button" value="+" id="green_plus">
</div>
<div id="input_div2">
<input type="button" value="-" id="brown_minus">
<input type="text" size="25" value="0" id="brown">
<input type="button" value="+" id="brown_plus">
</div>
<div id="input_div3">
<input type="button" value="-" id="blue_minus">
<input type="text" size="25" value="0" id="blue">
<input type="button" value="+" id="blue_plus">
</div>
<div id="input_div4">
<input type="button" value="-" id="yellow_minus">
<input type="text" size="25" value="0" id="yellow">
<input type="button" value="+" id="yellow_plus">
</div>
<div id="input_div5">
<input type="button" value="-" id="gold_minus">
<input type="text" size="25" value="0" id="gold">
<input type="button" value="+" id="gold_plus">
</div>
<div id="input_div6">
<input type="button" value="-" id="red_minus">
<input type="text" size="25" value="0" id="red">
<input type="button" value="+" id="red_plus">
</div>
</div>
</body>
</html>
I have made a variaton adding dinamically colors using an input so you can call any color name you want.
Put the buttons above each color is kinda dificult because you are using a polygon, so in this example the button are in the left side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Colour counter</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/Main.js"></script>
<style>
.grid {
display: flex;
text-align: center;
max-width: 480px;
}
.grid .counter {
margin-right: 15px;
}
.counter .column {
text-align: center;
vertical-align: middle;
}
.column {
height: 100px;
width: 100px;
display: flex;
align-content: center;
justify-content: center;
align-items: center;
}
.form {
margin: 10px 0;
}
.form input[type='text'] {
margin: 3px 0;
border: 1px solid black;
width: 200px;
}
input[type='button'] {
border: 1px solid black;
margin: 0 4px;
}
.pyramid {
clip-path: polygon(50% 0, 100% 100%, 0 100%);
width: 300px;
aspect-ratio: 9 / 15;
/* 2/1 */
background-color: white;
display: grid;
grid-template-columns: 1fr;
}
.pyramid>* {
background: white;
}
.counter input[type=button],
input[type=text] {
display: inline-block;
width: 20px;
background-color: transparent;
outline: none;
border: none;
text-align: center;
cursor: pointer;
padding: 0px;
color: black;
height: 33px;
font-family: 'Open Sans';
}
#container {
width: 100px;
height: 100px;
position: relative;
}
button {
border-radius: 50%;
}
</style>
</head>
<body>
<div class="color-counter">
<h1>Colour counter</h1>
</div>
<div class="form">
<form>
<label for="fcolour">Enter the colour name: </label>
<br>
<input id="fcolour" type="text" name="fcolour">
<br>
<input type="button" value="Submit">
</form>
</div>
<div id="container">
<div class="grid">
<div class="counter">
</div>
<div class="pyramid">
</div>
</div>
</div>
<script>
document.querySelector('form input[type="button"]').addEventListener('click', function (e) {
var colCounter = document.querySelector('.grid .counter')
var colPyramid = document.querySelector('.grid .pyramid')
var colorName = document.getElementById('fcolour').value
var newCounterChild = document.createElement('div')
newCounterChild.classList.add('column')
newCounterChild.innerHTML = `
<input type="button" value="-" id="minus_${colorName}">
<input type="text" size="25" value="0" id=counter_${colorName}>
<input type="button" value="+" id="plus_${colorName}">
`
colCounter.appendChild(newCounterChild)
var newPyramidChild = document.createElement('div')
newPyramidChild.classList.add('column')
newPyramidChild.style.backgroundColor = colorName
newPyramidChild.style.marginTop = '10px'
colPyramid.appendChild(newPyramidChild)
document.getElementById(`plus_${colorName}`).addEventListener('click', function (v) {
document.getElementById(`counter_${colorName}`).value++
})
document.getElementById(`minus_${colorName}`).addEventListener('click', function (v) {
var val = document.getElementById(`counter_${colorName}`)
val.value > 0 ? val.value-- : null
})
})
</script>
</body>

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