How would i align my image above everything else on the page? - javascript

I'm trying to get this image, which will end up being a logo, to appear above the table. Everything i have tried has just moved the image beside the other content rather than above it.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
main {
background-color: #1e1f1f;
display: inline-block;
padding: 25px;
font-size: 1.4rem;
font-family: Arial, Helvetica, sans-serif;
}
#myInput {
padding: 0;
margin: 0;
border: none;
width: 100%;
display: block;
font-size: 1.4rem;
text-align: center;
}
#myInput:focus {
outline:none;
text-align: center;
}
header label {
display:block;
text-align: center;
}
header strong {
box-sizing: border-box;
display: block;
padding: 15px 8px;
margin-bottom: 15px;
background: white;
width: 100%;
text-align: center;
}
main>div>div,
header div {
padding: 15px 18px;
background: white;
margin-bottom: 65px;
}
main>div>div {
margin: 25px 0;
padding: 15px 8px;
}
main>div>div>strong {
display: inline-block;
text-align:center;
}
output {
display: inline-block;
float: right;
text-align: right;
min-width: 10em;
}
output::before {
content: '£';
}
output::after {
clear: both;
content: '';
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
<body>
<main>
<header>
<img src="../Documents/RMS Logo - Oval.png" width="300" height="175" align="centre">
<label>
<strong>Enter NHS Price Below</strong>
<div>
<input id="myInput"/>
</div>
</label>
</header>
<div>
<div>
<strong>Retail:</strong>
<output id="output1" />
</div>
<div>
<strong>Schools & CDC's:</strong>
<output id="output2" />
</div>
<div>
<strong>Trade - Band A:</strong>
<output id="output3" />
</div>
<div>
<strong>Trade - Band B:</strong>
<output id="output4" />
</div>
<div>
<strong>Trade - Band C:</strong>
<output id="output5" />
</div>
<div>
<strong>Trade - Band D:</strong>
<output id="output6" />
</div>
</div>
</main>
<script type="text/javascript">
function byId(id) {
return document.getElementById(id)
}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt) {
let outputs = [byId('output1'), byId('output2'), byId('output3'), byId('output4'), byId('output5'), byId('output6')];
let value = parseFloat(this.value);
if (!isNaN(value)) {
outputs[0].textContent = Math.ceil(value / 0.7);
outputs[1].textContent = Math.ceil(value * 1);
outputs[2].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 40));
outputs[3].textContent = Math.ceil(value * 1);
outputs[4].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 20));
outputs[5].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 10));
} else {
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent =
outputs[3].textContent =
outputs[4].textContent =
outputs[5].textContent = "*Please Enter a Number*";
}
}
</script>
</body>
</html>
I have tried aligning it to "top" and i cant find anything that makes it appear above, what would be the best and most simple way for me to move this image above?

Your HTML structure is wrong. The image shouldn't be inside the <head> tags. The head tag should be used for loading scripts for example. The <header> should not be repeated. I suggest to start by learning the basics of HTML structure here https://www.w3schools.com/html/html_intro.asp
That said, I've moved the image outside the head. I've placed the image inside the <header>. If you want to center the image, make the header 100% width, then apply display: block; to your image and margin: auto;.
See example below.
function byId(id) {
return document.getElementById(id)
}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt) {
let outputs = [byId('output1'), byId('output2'), byId('output3'), byId('output4'), byId('output5'), byId('output6')];
let value = parseFloat(this.value);
if (!isNaN(value)) {
outputs[0].textContent = Math.ceil(value / 0.7);
outputs[1].textContent = Math.ceil(value * 1);
outputs[2].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 40));
outputs[3].textContent = Math.ceil(value * 1);
outputs[4].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 20));
outputs[5].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 10));
} else {
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent =
outputs[3].textContent =
outputs[4].textContent =
outputs[5].textContent = "*Please Enter a Number*";
}
}
header {
width: 100%;
}
header img {
display: block;
margin: auto;
}
main {
background-color: #1e1f1f;
display: inline-block;
padding: 25px;
font-size: 1.4rem;
font-family: Arial, Helvetica, sans-serif;
}
#myInput {
padding: 0;
margin: 0;
border: none;
width: 100%;
display: block;
font-size: 1.4rem;
text-align: center;
}
#myInput:focus {
outline: none;
text-align: center;
}
header label {
display: block;
text-align: center;
}
header strong {
box-sizing: border-box;
display: block;
padding: 15px 8px;
margin-bottom: 15px;
background: white;
width: 100%;
text-align: center;
}
main>div>div,
header div {
padding: 15px 18px;
background: white;
margin-bottom: 65px;
}
main>div>div {
margin: 25px 0;
padding: 15px 8px;
}
main>div>div>strong {
display: inline-block;
text-align: center;
}
output {
display: inline-block;
float: right;
text-align: right;
min-width: 10em;
}
output::before {
content: '£';
}
output::after {
clear: both;
content: '';
}
<!DOCTYPE html>
<html>
<head>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<main>
<header>
<img src="../Documents/square.jpg" width="300" height="175" align="top">
</header>
<div>
<div>
<strong>Enter NHS Price Below</strong>
<input id="myInput" />
</div>
<div>
<strong>Retail:</strong>
<output id="output1" />
</div>
<div>
<strong>Schools & CDC's:</strong>
<output id="output2" />
</div>
<div>
<strong>Trade - Band A:</strong>
<output id="output3" />
</div>
<div>
<strong>Trade - Band B:</strong>
<output id="output4" />
</div>
<div>
<strong>Trade - Band C:</strong>
<output id="output5" />
</div>
<div>
<strong>Trade - Band D:</strong>
<output id="output6" />
</div>
</div>
</main>
</body>
</html>

You can place it within your header tag but before the label
<header>
<img src="../Documents/square.jpg" width="300" height="175" align="top" >
<label>
<strong>Enter NHS Price Below</strong>
<div>
<input id="myInput"/>
</div>
</label>
</header>
you can also place it before the main tag which might be a bad practice though you might need to create a menu/nav-bar containing the image link
<nav>
<img src="../Documents/square.jpg" width="300" height="175" align="top" >
</nav>

I removed the image and create a class called image-top and added backgroud image their . Is this the thing are u asking about?
<!DOCTYPE html>
<html>
<head>
<!-- <img class="image-t" src="../Documents/square.jpg" width="300" height="175" align="top" > -->
</head>
<style>
main {
background-color: #1e1f1f;
display: inline-block;
padding: 25px;
font-size: 1.4rem;
font-family: Arial, Helvetica, sans-serif;
}
.image-top{
height: 50vh;
background-image: url('https://www.hackingwithswift.com/uploads/matrix.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
#myInput {
padding: 0;
margin: 0;
border: none;
width: 100%;
display: block;
font-size: 1.4rem;
text-align: center;
}
#myInput:focus {
outline:none;
text-align: center;
}
header label {
display:block;
text-align: center;
}
header strong {
box-sizing: border-box;
display: block;
padding: 15px 8px;
margin-bottom: 15px;
background: white;
width: 100%;
text-align: center;
}
main>div>div,
header div {
padding: 15px 18px;
background: white;
margin-bottom: 65px;
}
main>div>div {
margin: 25px 0;
padding: 15px 8px;
}
main>div>div>strong {
display: inline-block;
text-align:center;
}
output {
display: inline-block;
float: right;
text-align: right;
min-width: 10em;
}
output::before {
content: '£';
}
output::after {
clear: both;
content: '';
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
<body>
<div class="image-top">
<p>img</p>
</div>
<main>
<header>
<label>
<strong>Enter NHS Price Below</strong>
<div>
<input id="myInput"/>
</div>
</label>
</header>
<div>
<div>
<strong>Retail:</strong>
<output id="output1" />
</div>
<div>
<strong>Schools & CDC's:</strong>
<output id="output2" />
</div>
<div>
<strong>Trade - Band A:</strong>
<output id="output3" />
</div>
<div>
<strong>Trade - Band B:</strong>
<output id="output4" />
</div>
<div>
<strong>Trade - Band C:</strong>
<output id="output5" />
</div>
<div>
<strong>Trade - Band D:</strong>
<output id="output6" />
</div>
</div>
</main>
<script type="text/javascript">
function byId(id) {
return document.getElementById(id)
}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt) {
let input = byId('myInput');
input.addEventListener('input', onInputReceived, false);
}
function onInputReceived(evt) {
let outputs = [byId('output1'), byId('output2'), byId('output3'), byId('output4'), byId('output5'), byId('output6')];
let value = parseFloat(this.value);
if (!isNaN(value)) {
outputs[0].textContent = Math.ceil(value / 0.7);
outputs[1].textContent = Math.ceil(value * 1);
outputs[2].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 40));
outputs[3].textContent = Math.ceil(value * 1);
outputs[4].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 20));
outputs[5].textContent = Math.ceil(value / 0.7 - (value / 0.7 / 100 * 10));
} else {
outputs[0].textContent =
outputs[1].textContent =
outputs[2].textContent =
outputs[3].textContent =
outputs[4].textContent =
outputs[5].textContent = "*Please Enter a Number*";
}
}
</script>
</body>
</html>

To move something above something use position: relative or position: absolute and add z-index higher, than element after it.
E.g.:
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute;
left: 10px;
top: 10px;
z-index: 1;
}
</style>
</head>
<body>
<img src="https://via.placeholder.com/150">
<p>Text after image Text after image Text after image Text after image Text after image Text after image Text after image</p>
</body>
</html>
If that not your question, sorry, I did not correctly understand :)

Related

Vanilla JS budget app delete dynamically rendered income or expense

I've made a budgeting app that has expenses and Income tabs. Every time you add an expense or income, the app pushes the information inside of an array of objects and dynamically renders an <li> component and places it inside of a <ul>. I'm having trouble with the edit and delete features. Each individual <li> comes with a delete and edit button. The <li>, delete button, and edit button all have the same id of Date.now(). Date.now() is used because it produces a number based on milliseconds and won't produce the same id twice unless someone types an expense or income twice within one millisecond I want to click on the delete button inside of the <li> and have my app remove that individual object from my entry_list[] array and also remove the <li> from the DOM.
'use strict'
const balanceElement = document.querySelector(".balance .value");
const totalIncome = document.querySelector(".income-total");
const totalOutcome = document.querySelector(".outcome-total");
const incomeElement = document.querySelector(".income-tab");
const expense = document.querySelector(".expense-tab");
const all = document.querySelector(".all-tab");
const incomeList = document.querySelector(".income-tab .list");
const expenseList = document.querySelector(".expense-tab .list");
const allList = document.querySelector(".all-tab .list");
const expensesButton = document.querySelector(".tab1");
const incomeButton = document.querySelector(".tab2");
const allButton = document.querySelector(".tab3");
const addExpense = document.querySelector(".add-expense")
const expenseTitle = document.querySelector(".expense-title-input")
const expenseAmount = document.querySelector(".expense-amount-input")
const addIncome = document.querySelector(".add-income")
const incomeTitle = document.querySelector(".income-title-input")
const incomeAmount = document.querySelector(".income-amount-input")
const list = document.querySelector('.list')
//SWITCHING BETWEEN TABS
expensesButton.addEventListener('click', () => {
expense.classList.remove('hidden');
incomeElement.classList.add('hidden');
expensesButton.classList.add('clicked');
incomeButton.classList.remove('clicked');
})
incomeButton.addEventListener('click', () => {
incomeElement.classList.remove('hidden');
expense.classList.add('hidden');
expensesButton.classList.remove('clicked');
incomeButton.classList.add('clicked');
})
incomeList.addEventListener('click', deleteOrEdit)
expenseList.addEventListener('click', deleteOrEdit)
let entry_list = []
addExpense.addEventListener('click', () =>{
if(expenseTitle.value == '' || expenseAmount.value == ''){
return;
}
let expense = {
type: 'expense',
title: expenseTitle.value,
amount: expenseAmount.value,
id: Date.now()
}
entry_list.push(expense)
clearExpense()
changeLists()
})
addIncome.addEventListener('click', () =>{
if(incomeTitle.value == '' || incomeAmount.value == ''){
return;
}
let income = {
type: 'income',
title: incomeTitle.value,
amount: incomeAmount.value,
id: Date.now()
}
entry_list.push(income)
clearIncome()
changeLists()
})
const clearExpense = () =>{
expenseTitle.value = '';
expenseAmount.value = '';
}
const clearIncome = () =>{
incomeTitle.value = ''
incomeAmount.value = ''
}
const changeLists = () =>{
expenseList.innerHTML = ''
incomeList.innerHTML = ''
entry_list.map((entry) =>{
if(entry.type == 'expense'){
return expenseList.innerHTML += `<li id = "${entry.id}" class= "${entry.type}">
<div class = "entry">${entry.title}: $${entry.amount}</div>
<div class="icon-container">
<div class = "edit" id="${entry.id}"></div>
<div class ="delete" id="${entry.id}"></div>
</div>
</li>`
}
else if(entry.type == 'income'){
return incomeList.innerHTML += `<li id = "${entry.id}" class= "${entry.type}">
<div class = "entry">${entry.title}: $${entry.amount}</div>
<div class="icon-container">
<div class = "edit" id="${entry.id}"></div>
<div class ="delete" id="${entry.id}"></div>
</div>
</li>`
}
})
addIncomes()
}
const addIncomes = () =>{
let sum = 0;
let income = 0;
let outcome = 0;
balanceElement.innerHTML = 0
totalIncome.innerHTML = 0
totalOutcome.innerHTML = 0
entry_list.forEach(list =>{
if(list.type == 'expense'){
sum -= list.amount
outcome -= list.amount
}else if(list.type == 'income'){
sum += Number(list.amount)
income += Number(list.amount)
}
balanceElement.innerHTML = '$' + sum
totalIncome.innerHTML = '$' + income
totalOutcome.innerHTML = '$' + outcome
})
}
// // DETERMINE IF BUTTON IS EDIT OR DELETE
function deleteOrEdit(e){
const targetButton = e.target;
const entry = targetButton.parentNode.parentNode;
if(targetButton.classList == ('delete')){
deleteEntry(entry)
}else if(targetButton.classList == ('edit')){
editEntry(entry);
}
}
// //DELETE FUNCTION
const deleteEntry = (entry) =>{
console.log(entry.id)
entry_list.splice(entry.id, 1)
// entry.innerHTML = ''
console.log(entry.id)
addIncomes()
}
// EDIT FUNCTION
const editEntry = (entry) =>{
let Entry = entry_list[entry.id]
if(entry.type == "income"){
incomeAmount.value = Entry.amount;
incomeTitle.value = Entry.title;
}else if(entry.type == "expense"){
expenseAmount.value = Entry.amount;
expenseTitle.value = Entry.title;
}
deleteEntry(entry);
}
#import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght#400;700&family=Raleway:wght#400;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Open Sans', sans-serif;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.budget-container{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
width: 100%;
background-color: #4F98CA;
}
.balance-container{
width: 360px;
height: 470px;
background-color: #50D890;
border-radius: 30px;
margin-right: 100px;
}
.app-title{
color: white;
margin-top: 1rem;
margin-left: 1rem;
}
.month{
color: white;
margin-top: 1rem;
text-align: center;
}
.budget-header{
display: flex;
flex-direction:column;
justify-content: center;
}
.balance{
margin-top: 1rem;
margin-left: 1rem;
}
.title{
color: white;
font-size: 1.25rem;
opacity: .75;
}
.value{
font-size: 1.75rem;
color: white;
font-weight: bold;
margin-left: 1rem;
}
.account{
margin-top: 2.5rem;
margin: 2.5rem 1.5rem 2.5rem 1.5rem;
display: flex;
justify-content: space-between
}
.income-total{
color: white;
text-align: center;
font-size: 1.5rem;
}
.outcome-total{
color: #4F98CA;
text-align: center;
font-size: 1.5rem;
}
/* DASHBOARD */
.budget-dashboard{
display: block;
width: 360px;
height: 470px;
position: relative;
border-radius: 30px;
background-color: white;
}
.dash-title{
margin-top: 2rem;
margin-left: 1rem;
font-size: 1.5rem;
}
.toggle{
margin: 1rem;
display: flex;
cursor: pointer;
}
.toggle .tab2, .tab3{
margin-left: 1rem;
cursor: pointer;
}
.clicked{
font-weight: bold !important;
}
.hidden{
display: none !important;
}
/* EXPENSES TAB */
.expense-tab{
display: flex;
justify-content: center;
}
.expense-input-container{
position: absolute;
top: 400px;
border-top: solid 1px gray;
width: 100%;
}
.expense-amount-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.expense-title-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.add-expense{
color: none;
background-color: none;
border: none;
outline: none;
color: inherit;
}
/* INCOME TAB */
.income-tab{
display: flex;
justify-content: center;
}
.income-input-container{
position: absolute;
top: 400px;
border-top: solid 1px gray;
width: 100%;
}
.input{
display: flex;
justify-content: space-between;
align-items: center;
margin: 1rem;
}
.income-amount-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.income-title-input{
width: 125px;
border: none;
outline: none;
font-size: 1.25rem;
}
.add-income{
color: none;
background-color: none;
border: none;
outline: none;
}
.plus-img{
width: 40px;
}
/* li */
ul{
width: 360px;
height: 255px;
list-style: none;
margin-top:20px;
overflow-x: auto;
}
/* BUTTON ICONS */
.edit{
background-image: url('media/Icons/icons8-edit-48.png');
background-size: contain;
width: 25px;
height: 25px;
background-repeat: no-repeat;
margin-right: 10px;
}
.delete{
background-image: url('media/Icons/icons8-trash-can-48 (2).png');
background-size: contain;
width:25px;
height: 25px;
background-repeat: no-repeat;
}
.income{
width:250px;
height: auto;
padding-left: 20px;
margin-bottom: 10px;;
word-wrap: break-word;
color: black
}
.expense{
width:250px;
height: auto;
padding-left: 20px;
margin-bottom: 10px;;
word-wrap: break-word;
font-family: 'Gilroy Bold';
color: #4F98CA;
}
li{
display: flex;
justify-content: space-between;
width: 100% !important;
padding-right: 20px;
}
.icon-container{
display: flex;
}
#media (max-width:900px){
.budget-container{
display: inline-block;
position: relative
}
.balance-container{
position: absolute;
top: 10%;
left: 25%;
}
.budget-dashboard{
position: absolute;
left: 25%;
top: 40%;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Budgetrr</title>
</head>
<body>
<main class="budget-container">
<section class="balance-container">
<div class="app-title">
<p>Budgetrr</p>
</div>
<h1 class="month">OCTOBER</h1>
<section class="budget-header">
<div class="balance">
<div class="title">
Balance
</div>
<div class="value">
<small>$</small>0
</div>
</div>
<div class="account">
<div class="budget-income">
<div class="title">
Income
</div>
<div class="income-total">
<small>$</small>0
</div>
</div>
<div class="chart"></div>
<div class="budgetoutcome">
<div class="title">
Expenses
</div>
<div class="outcome-total">
<small>$</small>0
</div>
</div>
</div>
</section>
</section>
<section class="budget-dashboard">
<div class="dash-title">Dashboard</div>
<div class="toggle">
<div class="tab1 clicked">Expenses</div>
<div class="tab2">Income</div>
<!-- <div class="tab3 clicked">All</div> -->
</div>
<div class="income-tab hidden">
<ul class="list"></ul>
<div class="income-input-container">
<form class="input">
<input type="text" class="income-title-input" name="title" placeholder="Title">
<input type="number" class="income-amount-input" name="amount" placeholder="$0">
<button type = "button" class="add-income"><img class= "plus-img"src="media/Icons/icons8-add-new-48.png" alt=""></button>
</form>
</div>
</div>
<div class = "expense-tab">
<ul class="list"></ul>
<div class="expense-input-container">
<div class="input">
<input type="text" class="expense-title-input" name="title" placeholder="Title">
<input type="number" class="expense-amount-input" name="amount" placeholder="$0">
<button type="button" class="add-expense"><img class= "plus-img" src="media/Icons/icons8-add-new-48.png" alt=""></button>
</div>
</div>
</div>
</section>
</main>
<script src="JavaScript/budget.js"></script>
</body>
</html>
I've tried to use .splice() but I can't seem to get it to work.
Your entry is an object. And entry has an id property with Date type.
Your delete function calls this:
entry_list.splice(entry.id, 1)
Javascript splice function
function takes number as argument(s).
You should find the id of element you want to delete and get its index. After that you can delete the element with splice method.
Here is how to delete:
// Find the index of object at the given list
const index = entry_list.findIndex(x => x.id === entry.id);
// Starting from index of element to delete, remove 1 element.
entry_list.splice(index, 1);

Autofocus after <input> and again after all inputs

Creating a check for entered numbers on the right div with random numbers on the left div
I don't understand how to make sure that:
after entering smth in the first input, it must focus on the second and etc.
And how after all filled inputs, it must focus again on the first input
sorry for my english
do not offer jquery, please
'use strict';
let codeNum = document.querySelectorAll('.codeNumber'),
inputNum = document.querySelectorAll('input');
function randomCode() {
codeNum.forEach(function(item) {
item.textContent = randomInteger(0, 9);
})
function randomInteger(min, max) {
// получить случайное число от (min-0.5) до (max+0.5)
let rand = min - 0.5 + Math.random() * (max - min + 1);
return Math.round(rand);
}
}
randomCode();
let new1 = [];
let new2 = [];
function checkInput() {
for (var i=0;i<codeNum.length;i++) {
new1[i] = codeNum[i].innerHTML;
new2[i] = inputNum[i].value;
}
if (JSON.stringify(new1)==JSON.stringify(new2)) {
randomCode();
}
console.log(JSON.stringify(new1));
console.log(JSON.stringify(new2));
}
for (var i=0;i<codeNum.length;i++) {
inputNum[i].addEventListener('input', checkInput)
}
#import url('https://fonts.googleapis.com/css?family=Raleway:200');
html, body {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: space-around;
height: 100%;
background: #1D1F20;
}
.text {
width: 25px;
height: 47px;
border: 1px solid #a7a7a7;
border-radius: 4px;
background-color: #1D1F20;
outline: none;
font-size: 2.5rem;
font-family: 'Raleway';
text-align: center;
color: #fff;
vertical-align: middle;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
/* display: none; <- Crashes Chrome on hover */
-webkit-appearance: none;
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}
span {
position: absolute;
top: 6%;
}
#box {
display: flex;
align-items: center;
justify-content: space-around;
width: 400px;
height: 200px;
color: white;
font-family: 'Raleway';
font-size: 2.5rem;
}
.gradient-border {
--borderWidth: 3px;
background: #1D1F20;
position: relative;
border-radius: var(--borderWidth);
}
.gradient-border:after {
content: '';
position: absolute;
top: calc(-1 * var(--borderWidth));
left: calc(-1 * var(--borderWidth));
height: calc(100% + var(--borderWidth) * 2);
width: calc(100% + var(--borderWidth) * 2);
background: linear-gradient(60deg, #f79533, #f37055, #ef4e7b, #a166ab, #5073b8, #1098ad, #07b39b, #6fba82);
border-radius: calc(2 * var(--borderWidth));
z-index: -1;
animation: animatedgradient 3s ease alternate infinite;
background-size: 300% 300%;
}
#keyframes animatedgradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pin-Pan! by Asad</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="gradient-border" id="box">
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
<div class="numbers codeNumber">1</div>
</div>
<div class="gradient-border box-2" id="box">
<span>password:</span>
<div class="numbers">
<input type="number" autofocus class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
<div class="numbers">
<input type="number" class="text" maxlength="1" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==1) return false;">
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>
I’m not sure if I understood you question, but here’s my approach:
I’ d use recursive functions to ensure it’s called after the user did something:
function rec(num){
if (num<NumberOfElements){
let el=document.querySelectorAll(".text")[num]//select current element
el.addEventListener("input", function(){//check for input
//do something
//. /do something
num++
rec(num)//recall the recursive function (“loop again”)
}
}}
I didn’t tried the code and you’ll have to customise this for your needs.

Javascript file partially running

So I taught myself coding a few years ago, and got it just enough to put together a few tools for work. I recently had to migrate my site out of CodePen and onto an actual web server. Now I'm having an issue where part of my javascript is executing properly (a portion that empties all other input fields when a user enters an input field using JQuery), but the button that calculates an answer will not work. I believe the .click is not picking it up. Either way I'm not getting error messages, the button just does nothing when I press it.
When I put the code in a snippet to share with you guys, it works (just like it did in CodePen), but the exact same code on my web host does not work. I'm really at a loss here and any help would be greatly appreciated. I feel like I'm missing some small line of code that's supposed to be included in all web files.
$(document).ready(function() {
//Clear out input fields when not selected
$("#sg").focusin(function() {
$("#density").val("");
});
$("#density").focusin(function() {
$("#sg").val("");
});
$("#pounds").focusin(function() {
$("#grams").val("");
$("#percentage").val("");
});
$("#grams").focusin(function() {
$("#percentage").val("");
$("#pounds").val("");
});
$("#percentage").focusin(function() {
$("#pounds").val("");
$("#grams").val("");
});
$(".input_field").focusin(function() {
$("#density").removeClass('highlight');
$("#sg").removeClass('highlight');
$("#pounds").removeClass('highlight');
$("#grams").removeClass('highlight');
$("#percentage").removeClass('highlight');
});
//Calculate on press of enter
$("#button").keypress(function(e) {
if (e.which == 13) {
alert("this is working");
}
});
$("#button").click(function() {
calculateButton();
});
//Calculate values on button hit
function calculateButton() {
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
function removeCommas(x) {
x = x.replace(",", "");
return x;
}
var results = 0;
//Pulling information from input cells
var densityStr = document.getElementById("density").value;
var sgStr = document.getElementById("sg").value;
var poundsStr = document.getElementById("pounds").value;
var gramsStr = document.getElementById("grams").value;
var percentageStr = document.getElementById("percentage").value;
//remove commas from string and then convert string to number
var densityNum = Number(removeCommas(densityStr));
var sgNum = Number(removeCommas(sgStr));
var poundsNum = Number(removeCommas(poundsStr));
var gramsNum = Number(removeCommas(gramsStr));
var percentageNum = Number(removeCommas(percentageStr));
if (densityStr.length !== 0) {
var sgConversion = densityNum / 8.3454;
$("#sg").val(sgConversion.toFixed(3));
$("#density").addClass('highlight');
} else if (sgStr.length !== 0) {
var densityConversion = sgNum * 8.3454;
$("#density").val(densityConversion.toFixed(3));
$("#sg").addClass('highlight');
}
if (poundsStr.length !== 0) {
$("#pounds").addClass("highlight");
densityNum = document.getElementById("density").value;
var gramsConversion = poundsNum * 119.83;
var percentageConversion = poundsNum / densityNum * 100;
$("#grams").val(gramsConversion.toFixed(0));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (gramsStr.length !== 0) {
$("#grams").addClass("highlight");
densityNum = document.getElementById("density").value;
var poundsConversion = gramsNum / 119.83;
var percentageConversion = poundsConversion / densityNum * 100;
$("#pounds").val(poundsConversion.toFixed(2));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (percentageStr.length !== 0) {
$("#percentage").addClass("highlight");
densityNum = document.getElementById("density").value;
var percentageDec = percentageNum / 100;
var poundsConversion = densityNum * percentageDec;
var gramsConversion = poundsConversion * 119.83;
$("#pounds").val(poundsConversion.toFixed(2));
$("#grams").val(gramsConversion.toFixed(2));
}
}
});
body {
margin: 0;
font-family: 'Lato', sans-serif;
background: #d2d2d2;
}
p {
text-align: center;
}
conatiner {
max-width: 1024px;
margin: 0 auto;
}
#navbarContainer {
background: #F44336;
overflow: hidden;
width: 100%;
margin: 0;
}
.navbar {
float: left;
display: block;
font-family: 'Lato', sans-serif;
height: 40px;
width: 200px;
line-height: 40px;
text-align: center;
background: #F44336;
text-decoration: none;
color: #212121;
}
.navbar:hover {
background: #E57373;
color: white;
}
.active {
background: #C62828;
color: white;
}
#formContainer {
width: 450px;
background: #FDFFFC;
margin: 50px auto;
padding: 0px;
border-radius: 8px;
overflow: hidden;
}
#formContainer header {
width: 100%;
height: 130px;
background-color: #3cba54;
overflow: auto;
color: white;
}
header h1 {
margin: 35px 0 0 0;
text-align: center;
line-height: 30px;
}
header h3 {
line-height: 40px;
text-align: center;
margin: 0;
}
#heading {
background-color: #3cba54;
height: 40px;
color: white;
margin-bottom: 25px;
margin-left: -30px;
}
#heading h3 {
line-height: 40px;
}
form {
padding: 20px 0 0 20px;
text-align: center;
}
label {
display: inline-block;
width: 220px;
text-align: right;
}
#myForm .input_field {
margin-left: 20px;
margin-bottom: 10px;
font-size: 20px;
padding-left: 10px;
width: 125px;
height: 35px;
font-size: 17px;
border-radius: 3px;
background-color: #E0E0E0;
border: none;
}
#button {
display: block;
border-radius: 6px;
width: 200px;
height: 50px;
padding: 8px 15px 8px 15px;
margin: 0 auto;
margin-bottom: 50px;
font-size: 16px;
box-shadow: 0 6px #540000;
background-color: #FF3636;
border: none;
outline: none;
}
#button:active {
background-color: #B81B1B;
box-shadow: 0 1px #27496d;
transform: translateY(5px);
}
.highlight {
background: #FFEB3B !important;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
</body>
</html>
Sometimes putting script tags before the elements on the page can cause issues. You can try to put the scripts at the bottom of the body like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

JS addition game: how do I display 4 possible answers, 3 of them are random and 1 is the correct answer ? (Codepen included)

I am building a game out of JS. the rules of the game are simple: you are asked what (num1) + (num2) equals (as you can see in the codepen).
In the game you have 4 possible choices to answer the question.
We're I'm stuck right now is creating those possible options: I would like to display three random numbers that are false and one number that is the correct sum.
my JS:
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
var options = {
option1: document.getElementById('option1'),
option2: document.getElementById('option2'),
option3: document.getElementById('option3'),
option4: document.getElementById('option4'),
}
Here is my codepen:
https://codepen.io/teenicarus/pen/Oxaaoe
How do i do this?
I appreciate all answers
The solution is a little complex, it will be so long to describe every row, so feel free to ask if anything isn't clear. Need to say, that the order of numbers on cards is randomly generated too. Here it is:
function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
function startGame() {
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
var otherNumbers = [];
var counter = 0;
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
var options = {
option1: document.getElementById('option1'),
option2: document.getElementById('option2'),
option3: document.getElementById('option3'),
option4: document.getElementById('option4'),
}
function generateRandomNumber() {
for (var i = 0; counter < 3; i++) {
var num = Math.floor((Math.random() * 30) + 10);
if (num !== result && counter < 3) {
counter++;
otherNumbers.push(num);
} else {
generateRandomNumber();
}
}
}
generateRandomNumber();
otherNumbers.push(result);
otherNumbers = shuffle(otherNumbers);
var arrCount = otherNumbers.length - 1;
for (var key in options) {
if (arrCount >= 0) {
options[key].innerHTML = otherNumbers[arrCount];
arrCount--;
}
}
}
startGame();
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 60px;
}
.App-header {
background-color: #222;
height: 180px;
padding: 20px;
color: white;
}
.App-intro {
font-size: large;
}
#keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.text-info {
color: #fff;
font-weight: bold;
font-size: 2.1rem;
}
.question {
font-size: 2rem;
}
.options {
margin: 5%;
display: flex;
margin-right: -12px;
margin-left: -12px;
flex-direction: row;
flex-wrap: wrap;
align-items: stretch;
flex: 1 0 auto;
}
.fields {
display: flex;
padding: 12px;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
flex: 1;
}
.field-block {
display: flex;
min-height: 160px;
padding: 10%;
flex-direction: row;
justify-content: center;
align-items: center;
/*flex: 1 0 auto;*/
border-radius: 4px;
background-color: #f9bad0;
font-size: 6rem;
color: #fff;
cursor: pointer;
}
.quiz {
color: #ddd;
margin: 2%;
background-color: #ec1561;
padding: 2%;
width: 90%;
position: relative;
}
.button {
display: flex;
height: 48px;
padding-right: 16px;
padding-left: 16px;
flex-direction: row;
justify-content: center;
align-items: center;
flex: 0 0 auto;
border-radius: 4px;
background-color: #2fcaaa;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .05), 0 2px 12px 0 rgba(0, 0, 0, .1);
transition: box-shadow 200ms ease-out;
color: #fff;
font-weight: 500;
text-align: center;
cursor: pointer;
}
.quiz .after {
position: absolute;
top: 5%;
left: 5%;
width: 90%;
height: 80%;
/*display: none;*/
color: #FFF;
text-align: center;
align-items: center;
justify-content: center;
display: flex;
opacity: 0.8;
font-size: 3rem;
}
.correct {
background-color: green;
}
.wrong {
background-color: #D91E18;
}
.hide {
display: none !important;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Adding 2 Numbers | Happy Learning!</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
</head>
<body>
<img alt="Join Slack" height="40" width="139" src="http://i.imgur.com/0Lne5Vr.png"/>
<div>
<h1>Adding Game</h1>
<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
</div>
<hr>
<div class="quiz">
<div class="quiz-content">
<div class="question">
What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
</div>
<div class="options">
<div class="fields animated zoomIn">
<div class="field-block" id="option1">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option2">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option3">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option4">
10
</div>
</div>
</div>
<div class="after hide" id="after">
</div>
<div class="play-again">
<a class="button" onclick="startGame()">Play Again</a>
</div>
</div>
</div>
<script src='index.js'></script>
</body>
</html>
Here is a solution you can refer.
document.addEventListener("DOMContentLoaded", function(event) {
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
var opts = [];
for(var i=0;i<3;i++){
opts.push(findRandom(result,opts));
}
opts.push(result);
opts.sort();
for(var i=1;i<5;i++){
document.getElementById('option'+i).innerHTML = opts[i-1];
}
});
function findRandom(n,opts){
var result = 0;
while(result !=n && result == 0){
result = Math.floor(Math.random() * (n + 1));
if(opts.indexOf(result) >0){
result = 0;
}
}
return result;
}
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 60px;
}
.App-header {
background-color: #222;
height: 180px;
padding: 20px;
color: white;
}
.App-intro {
font-size: large;
}
#keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.text-info {
color: #fff;
font-weight: bold;
font-size: 2.1rem;
}
.question {
font-size: 2rem;
}
.options {
margin: 5%;
display: flex;
margin-right: -12px;
margin-left: -12px;
flex-direction: row;
flex-wrap: wrap;
align-items: stretch;
flex: 1 0 auto;
}
.fields {
display: flex;
padding: 12px;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
flex: 1;
}
.field-block {
display: flex;
min-height: 160px;
padding: 10%;
flex-direction: row;
justify-content: center;
align-items: center;
/*flex: 1 0 auto;*/
border-radius: 4px;
background-color: #f9bad0;
font-size: 6rem;
color: #fff;
cursor: pointer;
}
.quiz {
color: #ddd;
margin: 2%;
background-color: #ec1561;
padding: 2%;
width: 90%;
position: relative;
}
.button {
display: flex;
height: 48px;
padding-right: 16px;
padding-left: 16px;
flex-direction: row;
justify-content: center;
align-items: center;
flex: 0 0 auto;
border-radius: 4px;
background-color: #2fcaaa;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .05), 0 2px 12px 0 rgba(0, 0, 0, .1);
transition: box-shadow 200ms ease-out;
color: #fff;
font-weight: 500;
text-align: center;
cursor: pointer;
}
.quiz .after {
position: absolute;
top: 5%;
left: 5%;
width: 90%;
height: 80%;
/*display: none;*/
color: #FFF;
text-align: center;
align-items: center;
justify-content: center;
display: flex;
opacity: 0.8;
font-size: 3rem;
}
.correct {
background-color: green;
}
.wrong {
background-color: #D91E18;
}
.hide {
display: none !important;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Adding 2 Numbers | Happy Learning!</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
</head>
<body>
<img alt="Join Slack" height="40" width="139" src="http://i.imgur.com/0Lne5Vr.png"/>
<div>
<h1>Adding Game</h1>
<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
</div>
<hr>
<div class="quiz">
<div class="quiz-content">
<div class="question">
What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
</div>
<div class="options">
<div class="fields animated zoomIn">
<div class="field-block" id="option1">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option2">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option3">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option4">
10
</div>
</div>
</div>
<div class="after hide" id="after">
</div>
<div class="play-again">
<a class="button">Play Again</a>
</div>
</div>
</div>
<script src='index.js'></script>
</body>
</html>
As per my comment, you will need to re-run that number generator to generate new and incorrect answers for the 3 remaining options. There are a few things that you want to watch out for:
You have to avoid collisions, i.e. do not generate numbers that are the same as the answer, or the same as any pre-generated incorrect options. We can make this simple check by using a while loop
You can use a generic function to generate num1 + num2, so that it can be re-used again to generate incorrect answers.
Instead of giving your options unique IDs, simply give them a generic class, e.g. <div class="field-block option"></div> . We want to be able to know how many options we have so that we generate correct number of answer + incorrect answers.
You might want to shuffle your answers array before appending them to the DOM, otherwise they will all have the first element containing the correct answer.
Side note: Although it is not mentioned in your original answer, I expected that you want to know which is the correct answer when a user click on that option. When a click event is fired from the option, you can simply get the index of the option, and check it against the answers array. If the option's index matches the index of the correct answer in the array, then you are good to go.
In the code snippet below, I have stripped the stylesheet and some unnecessary markup:
// FY shuffle
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
}
// Function that generates all options
var generateAllOptions = function() {
// Number generator
var getRandomNumber = function() {
return Math.floor((Math.random() * 30) + 10);
};
// Get the question + correct answer
var num1 = getRandomNumber();
var num2 = getRandomNumber();
var correctAnswer = num1 + num2;
var answers = [correctAnswer];
// Update question
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
// Generate incorrect answers/options, but make sure there are no collisions
var options = document.querySelectorAll('.options .option');
while(answers.length < options.length) {
var incorrectAnswer = getRandomNumber() + getRandomNumber();
if (answers.indexOf(incorrectAnswer) === -1)
answers.push(incorrectAnswer);
}
// Shuffle answers
shuffle(answers);
// Store index of correct answer
var correctIndex = answers.indexOf(correctAnswer);
// Append shuffled answers to options
for (var i = 0; i < options.length; i++) {
var option = options[i];
// Write answer values into innerHTML
option.innerHTML = answers[i];
// Bind click event to all options, use IIFE!
(function(idx) {
option.addEventListener('click', function() {
if (idx === correctIndex) {
alert('You have selected the right answer!');
} else {
alert('That is an incorrect answer.');
}
});
})(i);
}
};
generateAllOptions();
.option {
font-weight: bold;
background-color: steelblue;
color: #fff;
border-radius: 4px;
padding: 10px;
margin: 5px;
}
<div>
<h1>Adding Game</h1>
<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
</div>
<hr>
<div class="quiz">
<div class="quiz-content">
<div class="question">
What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
</div>
<div class="options">
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
</div>
<div class="after hide" id="after">
</div>
<div class="play-again">
<a class="button">Play Again</a>
</div>
</div>
</div>
Try this simple solution. This generates 4 unique random options out of which one option is the correct one. The option number of the correct answer is also random.
You only need to modify your js.
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
var ansIndex=(Math.floor((Math.random()*10))%4)+1; //this index will be the position of the correct answer
var option=[];
//the below loop fills the options array with random but unique options
for(var i=0;i<4;i++){
var temp=Math.floor((Math.random() * 30) + 10);
if(final.indexOf(temp)==(-1)){
option.push(temp);
continue;
}
else{
i--;
}
}
//finally the correct option is overwritten
option[ansIndex-1]=result;
var answer=document.getElementsByClassName("field-block");
answer[0].innerHTML=option[0];
answer[1].innerHTML=option[1];
answer[2].innerHTML=option[2];
answer[3].innerHTML=option[3];
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;

Javascript game help - counting with dice

For my assignment, I'm asked to create a game that uses JavaScript. Here is the premise of the game:
At the start of the game, there are ten chips. The player needs to distribute the chips between 11 squares. Each square is designated a number from two to 12. Once player has placed all the chips, he will roll two dice several times. The sum of the dice is recorded and a chip is removed from the corresponding square (if any). The number of rolls needed to remove all 10 chips marks the end of the game.
So I just began the assignment, but I am having trouble keeping a working tally of the number of rolls as it is happening. Parts of it are commented out as I was trying different things. Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
div.dice{
float:left;
width:32px;
background:#F5F5F5;
border:#999 1px solid;
padding:10px;
font-size:24px;
text-align:center;
margin:5px;
}
</style>
</head>
<body>
<script type "text/javascript">
function rollDice(){
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You rolled " + diceTotal;
}
var count = 0;
function displayTotal() {
count = parseInt(count) + parseInt(1);
var divData = document.getElementById("showCount");
divData.innerHTML = "Number of Rolls: " + count;
};
/**function displayTotal(val) {
var count = document.getElementById('count').value;
var new_count = parseInt(count, 10) + val;
if (new_count < 0) {new_count = 0;}
document.getElementById('count').value = new_count;
return new_count;
} *//
</script>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<button id = "roll" onclick="rollDice()">Roll Dice</button>
<div id ="showCount"></div>
<input type = "button" id = "roll" value = "Roll Dice" onclick = rollDice();/>
<h2 id="status" style="clear:left;"></h2>
</body>
</html>
Also, any suggestive information or links I should see to help with making the chips section (that gets subtracted from every time that total comes up on the die) would be extremely helpful. I have no idea how to do that. Also, how do I add one to the chip boxes on click, that's a mystery as well. I guess I could use some suggestions on counts in JS in general.
Thanks in advance for all the help!
UPDATE
I almost completed this dice game, it does everything the OP requested. I left only one minor thing undone:
Originally I had planned to dynamically remove the text that represented an array element as the real array element was actually removed. Other than that minor aesthetic flaw, it functions properly and it's UI ain't bad either.
I just remembered, there is one function I neglected to add was a reset function which is minor as well.
Plunker
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dice</title>
<style>
html,
body {
box-sizing: border-box;
font: 400 16px/1.5'Palatino Linotype';
height: 100vh;
width: 100vw;
overflow: hidden;
}
*,
*:before,
*:after {
box-sizing: inherit;
margin: 0;
padding: 0;
border: 0;
}
body {
background-color: #222;
color: #EFE;
font-variant: small-caps;
overflow: hidden;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.shell {
position: relative;
padding: 1.5em .75em;
margin: 0 auto;
height: 100%;
width: 100%;
}
.content {
postion: absolute;
font-variant: small-caps;
}
header {
width: 100%;
height: 40px;
position: relative;
margin-bottom: 1.5em;
}
h1 {
color: hsla(45, 100%, 60%, 1);
font-weight: 700;
line-height: 1;
letter-spacing: .5px;
font-size: 3rem;
margin: 0 0 2em 0;
}
.die1,
.die2 {
width: 48px;
height: 48px;
background-color: hsla(0, 100%, 50%, .6);
border-radius: 7px;
display: inline-table;
margin: 2em;
padding-left: 4px;
}
.pip div {
width: 8px;
height: 8px;
background-color: hsla(60, 100%, 80%, 1);
border-radius: 60px;
padding: 1px;
text-align: center;
}
.row {
width: 24px;
height: 8px;
}
.blank div {
width: 8px;
height: 8px;
padding: 1px;
text-align: center;
}
#tossed,
#reset {
height: 32px;
width: 64px;
color: hsla(180, 100%, 30%, 1);
border: 1px inset hsla(228, 100%, 50%, 1);
border-radius: 7px;
text-align: center;
font-size: 1.2rem;
font-variant: small-caps;
display: inline-table;
pointer-events: auto;
cursor: pointer;
}
#reset {
display: none;
}
#set {
display: table;
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
border: 1px ridge hsla(48, 100%, 50%, 1);
border-radius: 7px;
padding: 5px;
}
#field {
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
border: 1px ridge hsla(48, 100%, 50%, 1);
border-radius: 7px;
padding: 5px;
}
.subFieldset {
pointer-events: none;
}
legend {
color: hsla(45, 100%, 60%, 1);
font-size: 1.5rem;
margin: 0 4em 0 0;
pointer-events: none;
}
#set input {
width: 48px;
height: 32px;
background-color: hsla(0, 0%, 80%, 1);
color: hsla(240, 100%, 40%, 1);
font-family: 'Source Code Pro';
font-size: 1rem;
border: 1px inset hsla(192, 100%, 50%, 1);
border-radius: 7px;
margin: 3px;
padding: 3px;
cursor: pointer;
pointer-events: auto;
display: table-cell;
}
label {
margin: 0 10px 0 0;
font-variant: normal;
display: inline-table;
color: hsla(60, 100%, 80%, 1);
pointer-events: none;
}
output {
color: hsla(240, 100%, 50%, 1);
font-family: 'Source Code Pro';
pointer-events: none;
}
#slotDisplay {
display: table-row;
float: left;
clear: both;
margin: 1em auto;
background-color: hsla(0, 0%, 20%, 1);
border: 1px inset hsla(45, 100%, 60%, 1);
border-radius: 7px;
color: hsla(48, 100%, 50%, 1);
width: 100%;
max-width: 760px;
min-width: 320px;
line-height: 1;
padding: 5px;
font-size: 1.5rem;
pointer-events: none;
}
</style>
</head>
<body>
<header>
<h1>Dice</h1>
</header>
<section class="shell">
<main class="content">
<section class="box">
<fieldset id="field">
<input id="reset" type="reset" value="Reset">
<label for="scored thrown">Score:
<output id="scored" name="scored" for="ui" form="ui">00</output>
/ Rolls:
<output id="thrown" name="thrown" for="ui" form="ui">00</output>
</label>
<button id="tossed" enabled="false">Roll</button>
</fieldset>
<table class="die1">
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
</table>
<table class="die2">
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
</table>
</section>
<form id="ui">
<fieldset id="set">
<legend>Distribute Chips in any Combination</legend>
<label>Chips Remaining:
<output id="wallet" name="wallet" for="ui" form="ui">10</output>
</label>
<br/>
<section class="subFieldset">
<label>
<input type="button" id="b-2" class="feed" value="02" form="ui">
</label>
<label>
<input type="button" id="b-3" class="feed" value="03" form="ui">
</label>
<label>
<input type="button" id="b-4" class="feed" value="04" form="ui">
</label>
<label>
<input type="button" id="b-5" class="feed" value="05" form="ui">
</label>
<label>
<input type="button" id="b-6" class="feed" value="06" form="ui">
</label>
<label>
<input type="button" id="b-7 " class="feed" value="07" form="ui">
</label>
<label>
<input type="button" id="b-8" class="feed" value="08" form="ui">
</label>
<label>
<input type="button" id="b-9" class="feed" value="09" form="ui">
</label>
<label>
<input type="button" id="b-10" class="feed" value="10" form="ui">
</label>
<label>
<input type="button" id="b-11" class="feed" value="11" form="ui">
</label>
<label>
<input type="button" id="b-12" class="feed" value="12" form="ui">
</label>
</section>
<textarea id="slotDisplay" readonly cols="30" rows="1" form="ui"></textarea>
</fieldset>
</form>
</main>
</section>
<script>
/*/////////////][ GLOBAL ][//////////////*/
var slots = [];
var chip = 10;
var roll = 0;
var set = document.getElementById("set");
/*/////////////][ PHASE I ][//////////////*/
set.addEventListener("click", execFeed, false);
function execFeed(event) {
if (event.target !== event.currentTarget) {
var tgt = event.target.id;
console.log('trueTarget: ' + tgt);
var feed = document.getElementById(tgt);
console.log('feed: ' + feed);
var val = feed.value;
console.log('val: ' + val);
var idx = parseInt(splitPop(tgt, '-'), 10) - 2;
console.log('idx: ' + idx);
chip = feedSlot(val, slots);
if (chip === 0) {
set.removeEventListener('click', execFeed, false);
tos.setAttribute('enabled', true);
var str0 = 'Roll the Dice to Match Each Number';
var col0 = 'lime';
msg(str0, col0);
}
}
event.stopPropagation();
}
function feedSlot(val, Arr) {
var wallet = document.getElementById('wallet');
var view = document.getElementById('slotDisplay');
Arr.push(val);
console.log('Arr: ' + Arr);
view.value = Arr;
chip--;
wallet.value = chip;
return chip;
}
var tos = document.getElementById('tossed');
/*/////////////][ PHASE II ][//////////////*/
tos.addEventListener('click', matchRoll, false);
function execRoll() {
var thrown = document.getElementById('thrown');
var scored = document.getElementById('scored');
var die1 = document.querySelector('.die1');
var die2 = document.querySelector('.die2');
var pip1 = selArr('td', die1);
var pip2 = selArr('td', die2);
var rd1 = rollDice(pip1);
var rd2 = rollDice(pip2);
var points = rd1 + rd2;
scored.value = leadZero(points, 2);
roll++;
thrown.value = leadZero(roll, 2);
return points;
}
function matchRoll() {
var val = execRoll();
var tgt = leadZero(val, 2);
console.log('execRoll: ' + tgt);
var arr = slots;
console.log('slots: ' + slots);
var mR = arr.indexOf(tgt);
if (mR === -1) {
var str1 = 'No Match, Roll Again';
var col1 = 'orange';
msg(str1, col1);
} else if (mR > -1 && chip < 9) {
++chip;
var toGo = 10 - chip;
var str2 = tgt + ' Matched, ' + toGo + ' More Matches Left';
var col2 = 'blue';
arr.splice(mR, 1);
msg(str2, col2);
} else {
++chip;
var exit = document.getElementById('reset');
var str3 = 'Completed in ' + roll + ' Rolls';
var col3 = 'yellow';
arr.splice(mR, 1);
msg(str3, col3);
exit.style.display = "block";
tos.style.display = "none";
}
wallet.value = chip;
return false;
}
function rollDice(arr) {
var ran6 = Math.floor(Math.random() * 6) + 1;
blank(arr);
switch (ran6) {
case 1:
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
break;
case 2:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 3:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 4:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 5:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 6:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[3].classList.remove('blank');
arr[3].classList.add('pip');
arr[5].classList.remove('blank');
arr[5].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
}
var pts = ran6;
return pts;
}
/*/////////////][ UTILITIES ][//////////////*/
function msg(str, col) {
var title = document.querySelector('legend');
title.style.color = col;
title.innerHTML = str;
}
function selArr(sel, ele) {
if (!ele) {
ele = document;
}
return Array.prototype.slice.call(ele.querySelectorAll(sel));
}
function blank(arr) {
for (var i = 0; i < arr.length; i++) {
arr[i].classList.remove('pip');
arr[i].classList.add('blank');
}
return false;
}
function leadZero(num, len) {
var str = num.toString();
var zeros = len - str.length;
for (var i = 1; i <= zeros; i++) {
str = "0" + str;
}
return str;
}
function splitPop(str, delim) {
var strX = str.split(delim).pop();
return strX;
}
</script>
</body>
</html>
OLD CONTENT
I made the fun part of this dice game, it's up to you, sir to finish the rest. JS is annotated, good luck.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dice</title>
<style>
html, body { box-sizing: border-box; font: 400 16px/1.5 'Source Code Pro'; height: 100vh; width: 100vw; }
*, *:before, *:after { box-sizing: inherit; margin: 0; padding: 0; border: 0; }
body { background-color: #222; color: #EFE; font-variant: small-caps; overflow: hidden; -webkit-tap-highlight-color: rgba(0,0,0,0); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
.shell { position: relative; padding: 1.5em .75em; margin: 0 auto; height: 100%; width: 100%; }
.content { postion: absolute; font-variant: normal; }
.die1, .die2 { width: 48px; height: 48px; background-color: hsla(0,100%,50%,.6); border-radius: 7px; display: inline-table; margin: 2em; padding-left: 4px; }
.pip div { width: 8px; height: 8px; background-color: hsla(60,100%,80%,1); border-radius: 60px; padding: 1px; text-align: center; }
.row { width: 24px; height: 8px; }
.blank div { width: 8px; height: 8px; padding: 1px; text-align: center; }
#toss { height: 32px; width: 64px; border: 1px inset hsla(0,0%,50%,1); border-radius: 6px; text-align: center; font-size: 1.2rem; font-variant: small-caps; display: inline-table; }
</style>
</head>
<body>
<header>
<h1>Dice</h1>
</header>
<section class="shell">
<main class="content">
<table class="die1">
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
</table>
<button id="toss">Roll</button>
<table class="die2">
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
</table>
</main>
</section>
<script>
// Reference to Dice (2 tables in DOM)
var die1 = document.querySelector('.die1');
var die2 = document.querySelector('.die2');
// Reference to Pips (2 arrays of table-cells in Dice) derived from selArr(sel, ele)☆
var pip1 = selArr('td', die1);
var pip2 = selArr('td', die2);
// Reference to the Toss (1 button triggers the random "roll" of the Dice)
var toss = document.getElementById('toss');
/*
** When the Toss button is clicked, execute function roll(arr)★ twice;
** once for the array of table cells (Pips) in table.die1 (Die One);
** then the other one in table.die2 (Die Two)
*/
toss.addEventListener('click', function(event) {
roll(pip1);
roll(pip2);
return false;
}, false);
/* ★
** Take the array of td (Pips) and add the .blank class to each of them ✪;
** generate a random number 1 thru 6 and determine the layout of the tds (pips)
*/
function roll(arr) {
blank(arr);
var ran6 = Math.floor(Math.random() * 6) + 1;
switch(ran6) {
case 1:
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
break;
case 2:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 3:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 4:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 5:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 6:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[3].classList.remove('blank');
arr[3].classList.add('pip');
arr[5].classList.remove('blank');
arr[5].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
}
}
/* ☆
** selArr(sel, ele) (selectorArray) this utility takes a collection of selectors
** and converts them into a real array
*/
function selArr(sel, ele) {
if(!ele) {
ele = document;
}
return Array.prototype.slice.call(ele.querySelectorAll(sel));
}
/* ✪
** blank(arr) takes an array of td (Pips) and adds the .blank class to each one of them
*/
function blank(arr) {
for(var i=0; i < arr.length; i++) {
arr[i].classList.remove('pip');
arr[i].classList.add('blank');
}
return false;
}
</script>
</body>
</html>

Categories