Couldn't align images to center - javascript

I am working on a project where couldn't align images to center. Rock-paper-scissor image align issue where I couldn't align the images to center from where I take responses to display.
let userScore = 0;
let computerScore =0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreboard_div = document.querySelector(".score-board");
const result_div = document.querySelector(".result");
const rock_div = document.getElementById("r")
const paper_div = document.getElementById("p")
const scissor_div = document.getElementById("s")
function getComputerChoice(){
const choices =['r','p','s'];
const randomNumber = Math.floor(Math.random()*3);
return choices[randomNumber];
}
function convertToWord(letter){
if(letter =="r") return "rock"
if(letter == "p") return "paper"
return "scissor"
}
getComputerChoice();
function win(userChoice,computerChoice){
userScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you win`
console.log("win " + userScore + ":" +computerScore);
}
function lose(userChoice,computerChoice){
computerScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you loose`
console.log("lose " + userScore + ":" +computerScore);
}
function draw(){
console.log("draw");
}
function game(userChoice){
const computerChoice = getComputerChoice();
switch (userChoice + computerChoice){
case "rs":
case "sp":
case "pr":
win();
break
case "sr":
case "ps":
case "rp":
lose();
break
case "rr":
case "pp":
case "ss":
draw();
break
}
}
function main(){
rock_div.addEventListener('click',function(){
game("r");
})
paper_div.addEventListener('click',function(){
game("p");
})
scissor_div.addEventListener('click',function(){
game("s");
})
}
main();
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
background-color: darkcyan;
}
header
{
background-color: whitesmoke;
padding: 20px;
}
header > h1 {
color:darkcyan;
text-align: center;
font-family: Asap, sans-serif;
}
.score-board{
margin: 20px auto;
border: 3px solid white;
border-radius: 10px;
text-align: center;
width:200px;
color: azure;
font-size: 46px;
position: relative;
}
.badge {
background: #50012e;
color: white;
font-size: 20px;
padding: 2px 10px;
font-family: Asap, sans-serif;
}
#user-label{
position: absolute;
top:15px;
left: -25px;
}
#computer-label{
position: absolute;
top:15px;
right: -25px;
}
.result{
font-size: 70px;
color: whitesmoke;
display: flex;
justify-content: center;
}
.result > p {
text-align: center ;
font-weight: bold;
font-family: Asap, sans-serif;
font-size: 20px;
}
.choices {
margin: auto;
text-align: center;
display: inline-block;
justify-content: center;
}
.choices{
border: 4px solid cyan;
border-radius: 50%;
margin:0 20px;
padding: 10px;
transition: all 0.2s ease;;
}
.choices:hover{
cursor: pointer;
background: #242424 ;
}
#action {
text-align: center;
color: azure;
font-weight: bold;
font-size: 20px;
margin-top: 20px;
font-family: Arial, Helvetica, sans-serif;
}
<html>
<head>
<meta charset="utf-8">
<title>
"Rock Paper Scissors"
</title>
<link rel="stylesheet" href="styles.css"></link>
</head>
<body>
<header>
<h1> Rock , Paper , Scissors </h1>
</header>
<div class="score-board">
<div id = "user-label" class = "badge">user</div>
<div id = "computer-label" class = "badge">comp</div>
<span id ="user-score">0</span>:<span id ="computer-score">0</span>
</div>
<div class="result">
<p>Scissor cuts paper,you win.!</p>
</div>
<div class="choices" id ="r">
<img src="assets/rock.PNG" alt="rock">
</div>
<div class="choices" id ="p">
<img src="assets/paper.PNG" alt="paper">
</div>
<div class="choices" id ="s">
<img src="assets/Scissor.PNG" alt="scissor">
</div>
<p id="action">Make Your Move</p>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
Image:

i think this solves your problem
let userScore = 0;
let computerScore =0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreboard_div = document.querySelector(".score-board");
const result_div = document.querySelector(".result");
const rock_div = document.getElementById("r")
const paper_div = document.getElementById("p")
const scissor_div = document.getElementById("s")
function getComputerChoice(){
const choices =['r','p','s'];
const randomNumber = Math.floor(Math.random()*3);
return choices[randomNumber];
}
function convertToWord(letter){
if(letter =="r") return "rock"
if(letter == "p") return "paper"
return "scissor"
}
getComputerChoice();
function win(userChoice,computerChoice){
userScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you win`
console.log("win " + userScore + ":" +computerScore);
}
function lose(userChoice,computerChoice){
computerScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you loose`
console.log("lose " + userScore + ":" +computerScore);
}
function draw(){
console.log("draw");
}
function game(userChoice){
const computerChoice = getComputerChoice();
switch (userChoice + computerChoice){
case "rs":
case "sp":
case "pr":
win();
break
case "sr":
case "ps":
case "rp":
lose();
break
case "rr":
case "pp":
case "ss":
draw();
break
}
}
function main(){
rock_div.addEventListener('click',function(){
game("r");
})
paper_div.addEventListener('click',function(){
game("p");
})
scissor_div.addEventListener('click',function(){
game("s");
})
}
main();
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
background-color: darkcyan;
}
header
{
background-color: whitesmoke;
padding: 20px;
}
header > h1 {
color:darkcyan;
text-align: center;
font-family: Asap, sans-serif;
}
.score-board{
margin: 20px auto;
border: 3px solid white;
border-radius: 10px;
text-align: center;
width:200px;
color: azure;
font-size: 46px;
position: relative;
}
.badge {
background: #50012e;
color: white;
font-size: 20px;
padding: 2px 10px;
font-family: Asap, sans-serif;
}
#user-label{
position: absolute;
top:15px;
left: -25px;
}
#computer-label{
position: absolute;
top:15px;
right: -25px;
}
.result{
font-size: 70px;
color: whitesmoke;
display: flex;
justify-content: center;
}
.result > p {
text-align: center ;
font-weight: bold;
font-family: Asap, sans-serif;
font-size: 20px;
}
.choices {
margin: auto;
text-align: center;
display: inline-block;
justify-content: center;
}
.choices{
border: 4px solid cyan;
border-radius: 50%;
margin:0 20px;
padding: 10px;
transition: all 0.2s ease;;
}
.choices:hover{
cursor: pointer;
background: #242424 ;
}
#action {
text-align: center;
color: azure;
font-weight: bold;
font-size: 20px;
margin-top: 20px;
font-family: Arial, Helvetica, sans-serif;
}
.choices-parent {
display: flex;
justify-content: center;
}
<html>
<head>
<meta charset="utf-8">
<title>
"Rock Paper Scissors"
</title>
<link rel="stylesheet" href="styles.css"></link>
</head>
<body>
<header>
<h1> Rock , Paper , Scissors </h1>
</header>
<div class="score-board">
<div id = "user-label" class = "badge">user</div>
<div id = "computer-label" class = "badge">comp</div>
<span id ="user-score">0</span>:<span id ="computer-score">0</span>
</div>
<div class="result">
<p>Scissor cuts paper,you win.!</p>
</div>
<div class="choices-parent">
<div class="choices" id ="r">
<img src="assets/rock.PNG" alt="rock">
</div>
<div class="choices" id ="p">
<img src="assets/paper.PNG" alt="paper">
</div>
<div class="choices" id ="s">
<img src="assets/Scissor.PNG" alt="scissor">
</div>
</div>
<p id="action">Make Your Move</p>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

Add all their images into one div and then apply css {text-align: center} to the newly added div.
<div class="new_div">
<div class="choices" id ="r">
<img src="assets/rock.PNG" alt="rock">
</div>
<div class="choices" id ="p">
<img src="assets/paper.PNG" alt="paper">
</div>
<div class="choices" id ="s">
<img src="assets/Scissor.PNG" alt="scissor">
</div>
</div>
And apply CSS
.new_div{
text-align: center;
}

use flex display for "chooise" scss class and use align-content "center"
you set flex display for pare

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

i am create Game tic tac toe but when Start game it's direct show winners name First Time after Run Game Completely

Code Link : https://github.com/henil11d/TicTacToi
Output : https://henil11d.github.io/TicTacToi/
You Check My Javascript Code On github page Solve My Problem
Problem is -:When Start Game Show Winner Name First Time after Program Run Completely
i am already Provided my code and output link please help.
You can update my code in GitHub page and help me
Source Code
Output
Please Help.
var c = 1;
function fil(elem) {
if (c <= 9) {
if (c % 2 != 0) {
document.getElementById(elem.id).innerHTML = "X";
d = 0;
}
else {
document.getElementById(elem.id).innerHTML = "O";
d = 1;
}
c++;
if (CkeckWin()) {
if (d == 0) {
alert("win X");
}else{
alert("win O");
}
reset();
}
} else {
alert("Match is Draw");
reset();
}
}
function reset() {
for (var i = 1; i <= 9; i++) {
document.getElementById("d" + i).innerHTML = "";
}
c = 1;
}
function CkeckWin() {
if (didvalue('d1', 'd2', 'd3') || didvalue('d1', 'd5', 'd9') || didvalue('d7', 'd8', 'd9') || didvalue('d1', 'd4', 'd7') ||
didvalue('d3', 'd6', 'd9') || didvalue('d3', 'd5', 'd7') || didvalue('d4', 'd5', 'd6') || didvalue('d2', 'd5', 'd8')) {
return true;
}
}
function didvalue(id1, id2, id3) {
if (getData(id1) != "" && getData(id2) != "" && getData(id3) != "" &&
getData(id1) == getData(id2) && getData(id2) == getData(id3)) {
return true;
}
}
function getData(Did) {
return document.getElementById(Did).innerHTML.trim();
}
*{
margin: 0;
padding: 0;
}
body{
background-color: rgb(44, 43, 43);
text-align: center;
user-select: none;
}
h1{
color: aqua;
font-size: 100px;
font-family: 'Courier New', Courier, monospace;
text-shadow: 0 0 6px rgb(234, 236, 122);
margin-top: 60px;
}
a{
font-family: sans-serif;
padding: 15px;
margin-right: 40px;
color: rgb(252, 252, 252);
background-color: rgb(84, 24, 224);
border-radius: 25px;
font-size: 28px;
box-shadow: 0 0 15px 0 rgb(19, 18, 18);
border-bottom-left-radius: 5px;
border-top-right-radius: 5px ;
text-decoration: none;
font-weight: bold;
}
a:hover{
color: black;
background-color: rgb(1, 198, 247);
border-radius: 28px;
box-shadow: 0 0 10px 0 rgb(13, 3, 160);
border-top-left-radius: 5px;
border-bottom-right-radius: 5px ;
}
a:active{
color: red;
}
.box{
border: 3px solid rgb(101, 250, 87);
height: 170px;
font-size: 140px;
width: 170px;
cursor: pointer;
color: rgb(3, 176, 182);
float: left;
}
.box:hover{
background-color: rgb(106, 109, 109);
}
.box:active{
background-color: antiquewhite;
}
.main{
position: relative;
top: 60px;
left: 140px;
width: 800px;
margin: auto;
/* display: none; */
}
#d1,#d4,#d7{
clear: left;
border-left: none;
}
#d1,#d2,#d3{
border-top: none;
}
#d3,#d6,#d9{
border-right: none;
}
#d7,#d8,#d9{
border-bottom: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Henil Code </title>
<link rel="stylesheet" href="Tecto.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"> </script>
<script src="te.js"> </script>
</head>
<body>
<!-- Henil Code -->
<h1> tic tac toe </h1>
<div class="main">
<div id="d1" class="box" onclick="fil(this)"> </div>
<div id="d2" class="box" onclick="fil(this)"> </div>
<div id="d3" class="box" onclick="fil(this)"> </div>
<div id="d4" class="box" onclick="fil(this)"> </div>
<div id="d5" class="box" onclick="fil(this)"> </div>
<div id="d6" class="box" onclick="fil(this)"> </div>
<div id="d7" class="box" onclick="fil(this)"> </div>
<div id="d8" class="box" onclick="fil(this)"> </div>
<div id="d9" class="box" onclick="fil(this)"> </div>
</div>
</body>
</html>
trim() function return like " " to ""
you need to add trim()
Change Code
function getData(Did) {
return document.getElementById(Did).innerHTML.trim();// trim() data
}

Having Trouble With JavaScript Location Reload

I'm creating my first JavaScript calculator, and I thought I could cheat on the clear button by reloading the page, but it doesn't seem to work. I have tried online editors, reopening chrome, moving files, and it still doesn't seem to work I don't know why, but help would be greatly appreciated.
EDIT: Sorry for taking so long, as you can see I now have the HTML and CSS to go with the JavaScript
var firstNumber = [];
var secondNumber = [];
let current = 'firstNumber';
var operation;
function clear(){
location.reload();
}
function set(number){
if (current == 'firstNumber'){
firstNumber.push(number);
}
else{
secondNumber.push(number);
}
document.getElementById('answer').innerHTML = number;
}
function change(operator){
current = 'secondNumber';
operation = operator;
if (operation == 'addition'){
return document.getElementById('answer').innerHTML = '+';
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = "-";
}
else if (operator == 'multiplication'){
return document.getElementById('answer').innerHTML = 'x';
}
else if (operator == 'multiplication'){
}
return document.getElementById("answer").innerHTML = '÷';
}
function solve(){
firstNumber = firstNumber.join('');
secondNumber = secondNumber.join('');
firstNumber = parseInt(firstNumber);
secondNumber = parseInt(secondNumber);
if (operation == 'addition'){
return document.getElementById("answer").innerHTML = firstNumber + secondNumber;
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = firstNumber - secondNumber;
}
else if (operation == 'multiplication'){
return document.getElementById("answer").innerHTML = firstNumber * secondNumber;
}
else if (operation == 'division'){
return document.getElementById('answer').innerHTML = firstNumber / secondNumber;
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
h1{
text-align: center;
font-family: monospace;
font-weight: bold;
font-size: 75px;
text-shadow: 3px 3px 15px red;
}
#container{
display: flex;
flex-direction: column;
width: 50%;
height: 500px;
margin-left: 25%;
}
.row{
display: flex;
flex-direction: row;
height: 15%;
margin-top: 1%;
width: 100%;
}
button{
width: 30%;
text-align: center;
margin: 5px;
font-size: 35px;
background-color: rgb(255, 0, 0);
border-color: purple;
}
#answer{
border-style: solid;
border-color: red;
border-width: 3px;
border-radius: 5px;
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
#wide{
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
body{
background-image: linear-gradient(to bottom right, rgb(0, 0, 255), rgb(100, 0, 255));
}
<!doctype html>
<html>
<head>
<title>Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" href="/static/calculator.css">
<script src="/static/calculator.js"></script>
</head>
<body>
<h1>Calculator</h1>
<br />
<div id="container">
<p id="answer"></p>
<button onclick="solve()" id="wide">=</button>
<div class="row">
<button onclick="set(1)">1</button>
<button onclick="set(2)">2</button>
<button onclick="set(3)">3</button>
</div>
<div class="row">
<button onclick="set(4)">4</button>
<button onclick="set(5)">5</button>
<button onclick="set(6)">6</button>
</div>
<div class="row">
<button onclick="set(7)">7</button>
<button onclick="set(8)">8</button>
<button onclick="set(9)">9</button>
</div>
<div class="row">
<button onclick="set(0)">0</button>
<button onclick="change('addition')">+</button>
<button onclick="change('subtraction')">-</button>
</div>
<div class="row">
<button onclick="change('multiplication')">x</button>
<button onclick="change('division')">/</button>
<button onclick="clear()">c</button>
</div>
</div>
</body>
</html>
It seems that clear() requires to bind an event listener in the DOM, for example:
<button id="clear">c</button>
<script>document.getElementById("clear").addEventListener("click", clear);</script>
Or, alternatively, use document.clear() (deprecated) or window.clear().
See related question:
Is "clear" a reserved word in Javascript?
https://developer.mozilla.org/en-US/docs/Web/API/Document/clear
To avoid that, simply rename clear() function to clearResult() and it will work.
See modified snippet below.
In addition, instead of location.reload(); you can simply clear content of the answer as a faster alternative:
document.getElementById('answer').innerHTML = '';
var firstNumber = [];
var secondNumber = [];
let current = 'firstNumber';
var operation;
function clearResult(){
location.reload();
}
function set(number){
if (current == 'firstNumber'){
firstNumber.push(number);
}
else{
secondNumber.push(number);
}
document.getElementById('answer').innerHTML = number;
}
function change(operator){
current = 'secondNumber';
operation = operator;
if (operation == 'addition'){
return document.getElementById('answer').innerHTML = '+';
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = "-";
}
else if (operator == 'multiplication'){
return document.getElementById('answer').innerHTML = 'x';
}
else if (operator == 'multiplication'){
}
return document.getElementById("answer").innerHTML = '÷';
}
function solve(){
firstNumber = firstNumber.join('');
secondNumber = secondNumber.join('');
firstNumber = parseInt(firstNumber);
secondNumber = parseInt(secondNumber);
if (operation == 'addition'){
return document.getElementById("answer").innerHTML = firstNumber + secondNumber;
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = firstNumber - secondNumber;
}
else if (operation == 'multiplication'){
return document.getElementById("answer").innerHTML = firstNumber * secondNumber;
}
else if (operation == 'division'){
return document.getElementById('answer').innerHTML = firstNumber / secondNumber;
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
h1{
text-align: center;
font-family: monospace;
font-weight: bold;
font-size: 75px;
text-shadow: 3px 3px 15px red;
}
#container{
display: flex;
flex-direction: column;
width: 50%;
height: 500px;
margin-left: 25%;
}
.row{
display: flex;
flex-direction: row;
height: 15%;
margin-top: 1%;
width: 100%;
}
button{
width: 30%;
text-align: center;
margin: 5px;
font-size: 35px;
background-color: rgb(255, 0, 0);
border-color: purple;
}
#answer{
border-style: solid;
border-color: red;
border-width: 3px;
border-radius: 5px;
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
#wide{
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
body{
background-image: linear-gradient(to bottom right, rgb(0, 0, 255), rgb(100, 0, 255));
}
<!doctype html>
<html>
<head>
<title>Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" href="/static/calculator.css">
<script src="/static/calculator.js"></script>
</head>
<body>
<h1>Calculator</h1>
<br />
<div id="container">
<p id="answer"></p>
<button onclick="solve()" id="wide">=</button>
<div class="row">
<button onclick="set(1)">1</button>
<button onclick="set(2)">2</button>
<button onclick="set(3)">3</button>
</div>
<div class="row">
<button onclick="set(4)">4</button>
<button onclick="set(5)">5</button>
<button onclick="set(6)">6</button>
</div>
<div class="row">
<button onclick="set(7)">7</button>
<button onclick="set(8)">8</button>
<button onclick="set(9)">9</button>
</div>
<div class="row">
<button onclick="set(0)">0</button>
<button onclick="change('addition')">+</button>
<button onclick="change('subtraction')">-</button>
</div>
<div class="row">
<button onclick="change('multiplication')">x</button>
<button onclick="change('division')">/</button>
<button onclick="clearResult()">c</button>
</div>
</div>
</body>
</html>

Keep unordered list aligned

I am working through a Udacity course on JavaScript. The main project is a resume built from a basic skeleton that the instructors provide as a GitHub repo. Here is a screenshot of my most recent version:
As you can see, my skills list moves to the left after it reaches the bottom of my picture. I want to keep the entire bulleted list lined up with the first two list items. How do I do this? Is it possible with the right <div>s or do I need a <table>?
Below is the relevant code:
index.html
<html>
<head>
<meta charset="utf-8">
<title>Resume</title>
<link href="css/style.css" rel="stylesheet">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<div id="main">
<div id="header" class="center-content clear-fix">
<ul id="topContacts" class="flex-box"></ul>
</div>
<div style="clear: both;"></div>
<div id="workExperience" class="gray">
<h2>Work Experience</h2>
</div>
<div id="projects">
<h2>Projects</h2>
</div>
<div id="education" class="gray">
<h2>Education</h2>
</div>
<div id="mapDiv">
<h2>Where I've Lived and Worked</h2>
</div>
<div id="lets-connect" class="dark-gray">
<h2 class="orange center-text">Let's Connect</h2>
<ul id="footerContacts" class="flex-box">
</ul>
</div>
</div>
<script src="js/jQuery.js"></script>
<script src="js/helper.js"></script>
<script src="js/resumeBuilder.js"></script>
<script>
if(document.getElementsByClassName('flex-item').length === 0) {
document.getElementById('topContacts').style.display = 'none';
}
if(document.getElementsByTagName('h1').length === 0) {
document.getElementById('header').style.display = 'none';
}
if(document.getElementsByClassName('work-entry').length === 0) {
document.getElementById('workExperience').style.display = 'none';
}
if(document.getElementsByClassName('project-entry').length === 0) {
document.getElementById('projects').style.display = 'none';
}
if(document.getElementsByClassName('education-entry').length === 0) {
document.getElementById('education').style.display = 'none';
}
if(document.getElementsByClassName('flex-item').length === 0) {
document.getElementById('lets-connect').style.display = 'none';
}
if(document.getElementById('map') === null) {
document.getElementById('mapDiv').style.display = 'none';
}
</script>
</body>
</html>
js/resumeBuilder.js
var dataPlaceHolder = "%data%";
var bio = {
"name" : "Code Apprentice",
"role" : "Software Engineer",
"contact" : {
"phone" : "555-555-5555",
"email" : "codeguru42#gmail.com",
"twitter" : "#codeguru42",
"github" : "codeguru42",
"location" : "Code Heaven"
},
"pictureURL" : "images/minion-me.png",
"welcomeMessage" : "Android Developer | Stack Overflow Contributor | Full Stack Web Developer",
"skills" : ["Java", "C++", "Android Development", "HTML", "JavaScript", "CSS", "Python"]
};
var formattedName = HTMLheaderName.replace(dataPlaceHolder, bio.name);
var formattedRole = HTMLheaderRole.replace(dataPlaceHolder, bio.role);
var formattedPhone = HTMLmobile.replace(dataPlaceHolder, bio.contact.phone);
var formattedEmail = HTMLemail.replace(dataPlaceHolder, bio.contact.email);
var formattedTwitter = HTMLtwitter.replace(dataPlaceHolder, bio.contact.twitter);
var formattedGithub = HTMLgithub.replace(dataPlaceHolder, bio.contact.github);var formattedPicture = HTMLbioPic.replace(dataPlaceHolder, bio.pictureURL);
var formattedLocation = HTMLlocation.replace(dataPlaceHolder, bio.contact.location);
var formattedBioPic = HTMLbioPic.replace(dataPlaceHolder, bio.pictureURL);
var formattedWelcomeMessage = HTMLwelcomeMsg.replace(dataPlaceHolder, bio.welcomeMessage);
var formattedSkills = bio.skills.map(function (skill) { return HTMLskills.replace(dataPlaceHolder, skill); });
$("#header").prepend(formattedRole);
$("#header").prepend(formattedName);
$("#header").prepend(formattedBioPic);
$("#header").append(formattedWelcomeMessage);
$("#header").append(HTMLskillsStart);
$("#header").append(formattedSkills);
$("#topContacts").append(formattedPhone);
$("#topContacts").append(formattedEmail);
$("#topContacts").append(formattedLocation);
$("#footerContacts").append(formattedTwitter);
$("#footerContacts").append(formattedGithub);
css/styles.css
body,
div,
ul,
li,
p,
h1,
h2,
h3,
h4,
h5,
h6 {
padding: 0;
margin: 0;
font-family: "Roboto", sans-serif;
}
.clear-fix {
overflow: auto;
}
.education-entry,
.work-entry,
.project-entry {
padding: 0 5%;
}
h1 {
font-size: 40px;
color: #f5a623;
line-height: 48px;
display: inline;
}
h2 {
font-weight: bold;
font-size: 24px;
color: #999;
line-height: 29px;
padding: 10px;
}
h3 {
font-style: italic;
font-size: 20px;
color: #000;
line-height: 22px;
}
h4 {
font-weight: bold;
font-size: 14px;
color: #4a4a4a;
line-height: 17px;
}
h2,
h3,
h4,
h5 {
padding: 10px 5%;
}
.date-text {
font-style: italic;
font-size: 14px;
color: #999;
line-height: 16px;
float: left;
}
.location-text {
font-style: italic;
font-size: 14px;
color: #999;
line-height: 16px;
float: right;
}
p {
font-size: 14px;
color: #333;
line-height: 21px;
}
a {
color: #1199c3;
text-decoration: none;
margin-top: 10px;
display: block;
}
.welcome-message {
font-style: italic;
font-size: 18px;
color: #f3f3f3;
line-height: 28px;
}
#skills-h3 {
color: #f5ae23;
display: none;
}
.orange {
background-color: #f5ae23;
}
.orange-text {
color: #f5ae23;
}
.white-text {
font-weight: bold;
color: #fff;
}
.gray {
background-color: #f3f3f3;
padding-bottom: 10px;
clear: both;
}
.dark-gray {
background-color: #4a4a4a;
}
/* TODO: Replace with image later */
#header {
background-color: #484848;
}
.flex-box {
display: -webkit-flex;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-around;
padding: 10px;
}
.flex-column {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
padding: 10px;
}
.center-content {
padding: 2.5% 5%;
}
ul {
list-style-type: none;
}
.biopic {
float: left;
padding: 10px;
width: 200px;
display: none;
}
img {
padding: 10px;
}
span {
padding: 5px;
}
#lets-connect {
text-align: center;
}
/* Media queries to handle various device widths */
#media only screen and (max-width: 1024px) {
#lets-connect {
margin-top: 5%;
}
}
#media only screen and (max-width:900px) {
.biopic {
width: 175px;
}
}
#media only screen and (max-width: 750px) {
#lets-connect {
margin-top: 10%;
}
.biopic {
width: 150px;
}
.welcome-message {
display: none;
}
}
#map {
display: block;
height: 100%;
margin: 0 5%;
}
#mapDiv {
height: 400px;
width: 100%;
padding-bottom: 5%;
}
#media only screen and (min-width: 750px) {
#skills-h3,
.biopic {
display: block;
}
}
js/helper.js
var HTMLheaderName = '<h1 id="name">%data%</h1>';
var HTMLheaderRole = '<span>%data%</span><hr>';
var HTMLcontactGeneric = '<li class="flex-item"><span class="orange-text">%contact%</span><span class="white-text">%data%</span></li>';
var HTMLmobile = '<li class="flex-item"><span class="orange-text">mobile</span><span class="white-text">%data%</span></li>';
var HTMLemail = '<li class="flex-item"><span class="orange-text">email</span><span class="white-text">%data%</span></li>';
var HTMLtwitter = '<li class="flex-item"><span class="orange-text">twitter</span><span class="white-text">%data%</span></li>';
var HTMLgithub = '<li class="flex-item"><span class="orange-text">github</span><span class="white-text">%data%</span></li>';
var HTMLblog = '<li class="flex-item"><span class="orange-text">blog</span><span class="white-text">%data%</span></li>';
var HTMLlocation = '<li class="flex-item"><span class="orange-text">location</span><span class="white-text">%data%</span></li>';
var HTMLbioPic = '<img src="%data%" class="biopic">';
var HTMLwelcomeMsg = '<span class="welcome-message">%data%</span>';
var HTMLskillsStart = '<h3 id="skills-h3">Skills at a Glance:</h3><ul id="skills" class="flex-column"></ul>';
var HTMLskills = '<li class="flex-item"><span class="white-text">%data%</span></li>';
Try to give clear:both to the image tag, so that the list does not move under the bottom of the picture.
After Inspecting the HTML elements in the generated page, I found that I was not correctly inserting <li> tags for each skill into the <ul> tag defined in HTMLskillsStart. I just had to change
$("#header").append(formattedSkills);
to
$("#skills").append(formattedSkills);

Display only one div at a time with JavaScript

I am just fooling around with some JavaScript, I am new to it so this is probably a simple solution. Basically what I want is for only 1 div to be visible at a time so if a user clicks on one link to expose a div the current div that is exposed will collapse and the new one clicked will appear.
I have included the code below:
<html>
<head>
<title> test</title>
<LINK href="blah.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript">
function toggle2(showHideDiv, switchTextDiv) {
var ele = document.getElementById(showHideDiv);
var text = document.getElementById(switchTextDiv);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "restore";
}
else {
ele.style.display = "block";
text.innerHTML = "collapse";
}
}
function toggle22(showHideDiv2, switchTextDiv2) {
var ele = document.getElementById(showHideDiv2);
var text = document.getElementById(switchTextDiv2);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "restore";
}
else {
ele.style.display = "block";
text.innerHTML = "collapse";
}
}
</script>
</head>
<body>
<div id="mainContent">
<div id="headerDiv">
<div id="titleText">Change Password - Click here ==></div><a id="myHeader" href="javascript:toggle2('myContent','myHeader');" >restore</a>
</div>
<div style="clear:both;"></div>
<div id="contentDiv">
<div id="myContent" style="display: none;">This is the content that is dynamically being collapsed.</div>
<!--DIV2 -->
<div id="headerDiv2">
<div id="titleText2">Change Username - Click here ==></div><a id="myHeader2" href="javascript:toggle22('myContent2','myHeader2');" >restore</a>
</div>
<div style="clear:both;"></div>
<div id="contentDiv2">
<div id="myContent2" style="display: none;">This is the content that is dynamically being collapsed.</div>
</div>
</div>
</body>
</html>
The CSS:
#headerDiv, #contentDiv {
float: left;
width: 510px;
}
#titleText {
float: left;
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#myHeader {
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#headerDiv {
background-color: #0037DB;
color: #9EB6FF;
}
#contentDiv {
background-color: #FFE694;
}
#myContent {
margin: 5px 10px;
}
#headerDiv a {
color: gold;
float: right;
margin: 10px 10px 5px 5px;
}
#headerDiv a:hover {
color: #FFFFFF;
}
#headerDiv2, #contentDiv2 {
float: left;
width: 510px;
}
#titleText2 {
float: left;
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#myHeader2 {
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#headerDiv2 {
background-color: #0037DB;
color: #9EB6FF;
}
#contentDiv2 {
background-color: #FFE694;
}
#myContent2 {
margin: 5px 10px;
}
#headerDiv2 a {
color: gold;
float: right;
margin: 10px 10px 5px 5px;
}
#headerDiv2 a:hover {
color: #FFFFFF;
}
style.display only reflects the style that's been explicitly set on the element. Unless you specify it with style="display:block" in HTML, the initial value of style.display will be empty, even though the default value of that property, applied by CSS cascading, is indeed block.

Categories