How To Reload The Web Page Using A Button In JavaScript - 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 ! :)

Related

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>

I am trying to insert a chunk of html code dynamically with Javascript reading smaple json, but unable to do so

Went through a few questions on stackoverflow but could not solve the error.
The intention is to modify and add html to the main document reading a JSON structure.
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Update 1:-
Typo was corrected, marked in code.
Defer was introduced at script load in head section, this makes sure the entire document is loaded before the script starts execution.
Here I am trying to read a JSON, and then looping across its content to add to my main html document.
var json={
"fruit":[
{
"fruitname":"Apple",
"location":"data/png/apple.png",
"quantity":"25",
"price":"2"
},
{
"fruitname":"Mango",
"location":"data/png/mango.png",
"quantity":"35",
"price":"3"
}
]
};
//var cards = document.getElementsByClassName("content"); -- corrected typo
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
var cardelement=document.createElement('div');
cardelement.className = 'card';
// alert(cardelement);
cards.appendChild(cardelement);
var object = document.createElement('div');
object.className = 'object';
// alert(object);
cardelement.appendChild(object);
var image = document.createElement('img');
image.setAttribute("src", fruits[i].location);
object.appendChild(image);
var objectback = document.createElement('div');
objectback.className = 'object-back';
cardelement.appendChild(objectback);
var backfruit = document.createElement('div');
backfruit.className = 'back-fruit';
backfruit.innerHTML = fruits[i].fruitname;
objectback.appendChild(backfruit);
var backprice = document.createElement('div');
backprice.className = 'back-price';
backprice.innerHTML = fruits[i].price + "$ per unit";
objectback.appendChild(backprice);
var backquantity = document.createElement('div');
backquantity.className = 'back-quantity';
backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
objectback.appendChild(backquantity);
}
*
{
margin: 0 0;
border: none;
text-align:center
}
#header
{
background-color: #F44336;
font-family: 'Bungee Shade', cursive;
font-size: 30px;
height: 20%
}
#footer
{
font-family: 'Roboto', sans-serif;
position: fixed;
height: 80%;
width: 100%
}
#content
{
width: 75%;
height: 100%;
border-right: thick solid #F44336;
float: left;
text-align: left;
overflow: scroll
}
#cart
{
background-color:#3F51B5;
width: 25%;
border-bottom: thick dashed #F44336;
float: right
}
.card
{
display:inline-block;
width: 100px;
height: 100px;
margin: 40px;
padding: 20px;
box-shadow: -1px 9px 20px 4px #000000;
border: 5px solid #F44336;
border-radius: 26px 26px 26px 26px;
transition: all .2s ease-in-out
}
.object .object-back
{
display:block;
position:static
}
.object-back
{
display: none
}
.object img
{
height: 100px;
width: 100px
}
.back-fruit
{
font-size: 20px;
padding-bottom: 5px;
margin-bottom: 10px;
border-bottom: thin solid
}
.back-price
{
font-size: 12px;
padding-bottom: 5px
}
.back-quantity
{
font-size: 10px;
padding-bottom: 10px
}
.back-pluscart
{
font-size: 15px;
background-color: #F44336;
width: auto
}
.back-pluscart img
{
height: 30px;
width: 30px
}
.card:hover
{
box-shadow: -1px 9px 46px 11px #000000
}
.card:hover .object
{
display: none
}
.card:hover .object-back
{
display:inline-block;
opacity: 1
}
<!DOCTYPE html>
<html>
<head>
<title> The Shopkeeper </title>
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel = "stylesheet" type = "text/css" href = "style/style.css" />
<script type="text/javascript" src="logic/core.js" defer></script>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="base">
<div id="header">
<h1> Fruitkart </h1>
</div>
<div id="footer">
<div id="content">
<!--
<div class="card">
<div class="object">
<img src="data/png/apple.png" />
</div>
<div class="object-back">
<div class="back-fruit">Apple</div>
<div class="back-price">2$ per unit</div>
<div class="back-quantity">In Stock 25 pieces </div>
<div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
</div>
</div>
-->
</div>
<div id="cart">
django
is a big boy
</div>
</div>
</div>
</body>
</html>
Why was content undefined
You try to get content by ClassName
var cards = document.getElementsByClassName("content")[0];
But find content in your html:
<div id="content">
Notice that the ID is content. Either change it to class="content" or change the previous code to document.getElementByID("content");
Two issues:
There is no element with class content. On the other hand there is an element with that id. So you probably want to do:
document.getElementById("content");
The script runs too soon -- the elements are not loaded yet when it runs. Either put the script just before the closing </body> tag, or put the code inside an event handler, like
window.addEventListener('DOMContentLoaded', function() {
// your code
});
You are trying to access an element with class name content var cards =document.getElementsByClassName("content")[0]; & there is no class named content
You can modify your code like this ,
var cards = document.getElementById("content");
var json={
"fruit":[
{
"fruitname":"Apple",
"location":"data/png/apple.png",
"quantity":"25",
"price":"2"
},
{
"fruitname":"Mango",
"location":"data/png/mango.png",
"quantity":"35",
"price":"3"
}
]
};
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
var cardelement=document.createElement('div');
cardelement.className = 'card';
// alert(cardelement);
cards.appendChild(cardelement);
var object = document.createElement('div');
object.className = 'object';
// alert(object);
cardelement.appendChild(object);
var image = document.createElement('img');
image.setAttribute("src", fruits[i].location);
object.appendChild(image);
var objectback = document.createElement('div');
objectback.className = 'object-back';
cardelement.appendChild(objectback);
var backfruit = document.createElement('div');
backfruit.className = 'back-fruit';
backfruit.innerHTML = fruits[i].fruitname;
objectback.appendChild(backfruit);
var backprice = document.createElement('div');
backprice.className = 'back-price';
backprice.innerHTML = fruits[i].price + "$ per unit";
objectback.appendChild(backprice);
var backquantity = document.createElement('div');
backquantity.className = 'back-quantity';
backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
objectback.appendChild(backquantity);
}
*
{
margin: 0 0;
border: none;
text-align:center
}
#header
{
background-color: #F44336;
font-family: 'Bungee Shade', cursive;
font-size: 30px;
height: 20%
}
#footer
{
font-family: 'Roboto', sans-serif;
position: fixed;
height: 80%;
width: 100%
}
#content
{
width: 75%;
height: 100%;
border-right: thick solid #F44336;
float: left;
text-align: left;
overflow: scroll
}
#cart
{
background-color:#3F51B5;
width: 25%;
border-bottom: thick dashed #F44336;
float: right
}
.card
{
display:inline-block;
width: 100px;
height: 100px;
margin: 40px;
padding: 20px;
box-shadow: -1px 9px 20px 4px #000000;
border: 5px solid #F44336;
border-radius: 26px 26px 26px 26px;
transition: all .2s ease-in-out
}
.object .object-back
{
display:block;
position:static
}
.object-back
{
display: none
}
.object img
{
height: 100px;
width: 100px
}
.back-fruit
{
font-size: 20px;
padding-bottom: 5px;
margin-bottom: 10px;
border-bottom: thin solid
}
.back-price
{
font-size: 12px;
padding-bottom: 5px
}
.back-quantity
{
font-size: 10px;
padding-bottom: 10px
}
.back-pluscart
{
font-size: 15px;
background-color: #F44336;
width: auto
}
.back-pluscart img
{
height: 30px;
width: 30px
}
.card:hover
{
box-shadow: -1px 9px 46px 11px #000000
}
.card:hover .object
{
display: none
}
.card:hover .object-back
{
display:inline-block;
opacity: 1
}
<!DOCTYPE html>
<html>
<head>
<title> The Shopkeeper </title>
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel = "stylesheet" type = "text/css" href = "style/style.css" />
<script type="text/javascript" src="logic/core.js" ></script>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="base">
<div id="header">
<h1> Fruitkart </h1>
</div>
<div id="footer">
<div id="content">
<!--
<div class="card">
<div class="object">
<img src="data/png/apple.png" />
</div>
<div class="object-back">
<div class="back-fruit">Apple</div>
<div class="back-price">2$ per unit</div>
<div class="back-quantity">In Stock 25 pieces </div>
<div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
</div>
</div>
-->
</div>
<div id="cart">
django
is a big boy
</div>
</div>
</div>
</body>
</html>

Creating a function to be called again and again

I want to create a simple text game of choices of sorts where you always have two choices and depending on your choice, something is displayed and the current content disappears. My problem is each of the choices are different so i can't figure out a way to not repeat myself again and again in the javascript code.
HTML :
<!Doctype html>
<html>
<head>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css"/>
<title>Game</title>
</head>
<body>
<div id="console">
<div class="storyCard" id="start">
<p class="q">Some stuff.
<p class="a">getup</p>
<p class="a">sleep</p>
</div>
<div class="storyCard" id="getup">
<p class="q">Something happened</p>
<p class="a">do this</p>
<p class="a">do that</p>
</div>
<div class="storyCard" id="sleep">
<p class="q">something else happened</p>
<p class="a">do something</p>
<p class="a">do something else</p>
</div>
<!--and there will be a lot of such storyCards based on the choices.-->
</div>
<script type="text/javascript" src="js.js"></script>
</body>
</html>
CSS :
body {
margin: 0 auto;
align-content: center;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
}
#console {
width: 100%;
}
.storyCard {
min-width: 100px;
max-width: 600px;
background-color: rgba(0, 0, 0, 0.51);
box-shadow: 1px 1px 7px;
padding: 50px;
color: white;
margin: 0 auto;
border-radius: 4px;
display: none;
}
#start {
display: block;
}
.storyCard .a {
background-color: dodgerblue;
border-bottom-color: dodgerblue;
border-top-color: white;
border-left-color: white;
border-right-color: dodgerblue;
padding: 10px;
text-align: center;
color: white;
width: 30%;
display: inline;
margin: 0 auto;
box-shadow: 1px 1px 7px black;
float: right;
cursor: pointer;
}
.storyCard .a:hover {
background-color: white;
color: black;
}
}
Javascript :
document.querySelector('#console').addEventListener('click', function (e) {
var answer = e.target.textContent;
switch (answer) {
case 'getup':
e.target.parentNode.style.display = 'none';
document.querySelector('#getup').style.display = 'block';
break;
case 'sleep':
e.target.parentNode.style.display = 'none';
document.querySelector('#sleep').style.display = 'block';
break;
case 'do this':
e.target.parentNode.style.display = 'none';
/*display another content like above*/
case 'do that':
/*hide the current content again and display another content and add more cases*/
}, false);
I assume that the question must defined in html like your sample. There are many others way to do this better.
You can use class name to specify next question.
document.addEventListener('click', function (e) {
var target = e.target;
if (target.className.match('answer')) {
var nextQuestionId = target.className.replace('answer ', '');
hideAllStoryCards();
showStoryCard(nextQuestionId);
}
});
function hideAllStoryCards () {
var i, elm, elms = document.getElementsByClassName('storyCard');
for (i = 0; i < elms.length; i++) {
elm = elms[i];
elm.style.display = 'none';
}
}
function showStoryCard (id) {
var storyCard = document.getElementById(id);
storyCard.style.display = 'block';
}
hideAllStoryCards();
showStoryCard('first-question');
<div id="console">
<div class="storyCard" id="first-question">
<p class="q">Are you hungry?</p>
<p class="answer what-do-you-want-to-eat">yes</p>
<p class="answer may-i-help-you">no</p>
</div>
<div class="storyCard" id="what-do-you-want-to-eat">
<p class="q">Some stuff.</p>
<p class="answer NEXT_QUESTION_ID">a pie</p>
<p class="answer ANOTHER_QUESTION_ID">a buger</p>
</div>
<div class="storyCard" id="may-i-help-you">
<p class="q">Some stuff.</p>
<p class="answer NEXT_QUESTION_ID">bye</p>
<p class="answer ANOTHER_QUESTION_ID">bye again</p>
</div>
</div>
You can try something like performAction(e, '#getup'); - a generalized method with parameters, in this link.
Please refer below for the code:
HTML:
<div id="console">
<div class="storyCard" id="start">
<p class="q">Some stuff.</p>
<p class="a">getup</p>
<p class="a">sleep</p>
</div>
<div class="storyCard" id="getup">
<p class="q">Something happened</p>
<p class="a">do this</p>
<p class="a">do that</p>
</div>
<div class="storyCard" id="sleep">
<p class="q">something else happened</p>
<p class="a">do something</p>
<p class="a">do something else</p>
</div>
<!--and there will be a lot of such storyCards based on the choices.-->
</div>
CSS:
body {
margin: 0 auto;
align-content: center;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
}
#console {
width: 100%;
}
.storyCard {
min-width: 100px;
max-width: 600px;
background-color: rgba(0, 0, 0, 0.51);
box-shadow: 1px 1px 7px;
padding: 50px;
color: white;
margin: 0 auto;
border-radius: 4px;
display: none;
}
#start {
display: block;
}
.storyCard .a {
background-color: dodgerblue;
border-bottom-color: dodgerblue;
border-top-color: white;
border-left-color: white;
border-right-color: dodgerblue;
padding: 10px;
text-align: center;
color: white;
width: 30%;
display: inline;
margin: 0 auto;
box-shadow: 1px 1px 7px black;
float: right;
cursor: pointer;
}
.storyCard .a:hover {
background-color: white;
color: black;
}
JS:
document.querySelector('#console').addEventListener('click', function(e) {
var answer = e.target.textContent;
switch (answer) {
case 'getup':
performAction(e, '#getup');
break;
case 'sleep':
performAction(e, '#sleep');
break;
case 'do this':
performAction(e, '#getup'); /**Use any 'id' or target of your choice.*/
/*display another content like above*/
break;
case 'do that':
performAction(e, '#getup'); /*Use any 'id' or target of your choice.*/
/*hide the current content again and display another content and add more cases*/
break;
}
}, false);
function performAction(event, target) {
event.target.parentNode.style.display = 'none';
document.querySelector(target).style.display = 'block';
}
You need to separate your data from your UI.
Your data could be something simple like this:
var stories;
function StoryCard(q, option1, option2) {
this.q = q
this.option1 = option1;
this.option2 = option2;
}
function displayStory(storyCard) {
document.getElementById('q').innerHTML = storyCard.q;
document.getElementById('option1').innerHTML = storyCard.option1;
document.getElementById('option2').innerHTML = storyCard.option2;
}
Your "console" UI could change to something more like this:
<div id="console">
<div class="storyCard" id="start">
<p class="q" id="q"> </p>
<p class="a" id="option1"> </p>
<p class="a" id="option2"> </p>
</div>
</div>
Your click function may be more like this:
document.querySelector('#console').addEventListener('click', function (e) {
var answer = e.target.id;
switch (answer) {
default: // for when they click within the div, but not on an option
break;
case 'option1':
case 'option2':
var story = stories[e.target.innerHTML];
if (null != story) {
displayStory(story);
}
break;
}
}, false);
You would set up your stories perhaps in an onload:
function init() {
stories = { "start": new StoryCard("Some stuff", "getup", "sleep")
, "getup": new StoryCard("Something happened", "do this", "do that")
, "sleep": new StoryCard("something else happened", "do something", "do something else")
};
displayStory(stories["start"]);
}

javascript is will not run

I am trying to create a simple vote/poll program with javascript, I have tried to run it on xammp to see if it needed to be executed on a web server with no success. Do I need to include any script js files apart from vote.js like jquery or something? I am not sure.
Can someone help Thanks.
html
<!DOCTYPE html>
<html>
<head>
<title>Vote</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="vote.js"></script>
</head>
<body>
<div class="content">
<h3 class="title">Who's better ?</h3>
<ul>
<li class="option" id="option_1">
Messi
<p class="score" id="score_1">0</p>
<div class="progressbar">
</div>
</li>
<li class="option" id="option_2">
Ronaldo
<p class="score" id="score_2">0</p>
<div class="progressbar">
</div>
</li>
</ul>
</div>
</body>
</html>
css
.content {
background-color: #5C5C5C;
height: 500px;
width: 600px;
font-family: CorpidRegular,Arial,Helvetica,sans-serif;
color: #fff;
font-weight: normal;
font-size: 1.5rem;
}
.progressbar_1 {
width: 400px;
border-radius: 0px;
margin-left: 100px;
}
.progressbar_2 {
width: 400px;
border-radius: 0px;
margin-left: 100px;
}
h3{
text-align: center;
padding: 40px;
margin: 0px;
font-weight: normal;
}
ul{
list-style-type: none;
display: inline;
padding: 0px;
}
.option:first-child {
background: blue;
}
.option {
background: black;
}
li{
margin: 0px;
padding: 0px;
text-align: center;
color: #fff;
cursor: pointer;
}
li:hover {
color: yellow;
}
js
var totalVotes = 0;
$('.option').click(function() {
var $this = $(this);
// store voting value in data-voting
if (!$this.data('voting'))
$this.data('voting', 0);
var voting = parseInt($this.data('voting'), 10);
voting++;
totalVotes++;
$this.data('voting', voting);
updateProgressBars();
});
function updateProgressBars()
{
$('.option').each(function()
{
var $this = $(this);
var voting = parseInt($(this).data('voting'), 10);
var pct = Math.round((voting / totalVotes) * 100);
if (isNaN(voting)) voting = 0;
if (isNaN(pct)) pct = 0;
$this.find('progressbar').progressbar({value: pct});
$this.find('.score').html(voting + ' of ' + totalVotes + ' (' + pct + '%)');
});
}
You only close html tag, didin't open tag

Categories

Resources