Know when each element have same CSS property value - javascript

I'm making a form using some circles to show the user whether the field is correctly filled or not.
I want to be able to know when all of the circles are green to then change the SUBMIT button background-color.
If you didn't understand just run the snippet full screen and you'll see.
// Système de toggleBox
var toggleCanvas = document.getElementById('newsteller');
let n_state = true;
function toggleNewsteller() {
if (getComputedStyle(document.getElementById('newsteller')).backgroundColor == "rgb(180, 223, 180)") {
n_state = false;
} else {
n_state = true;
}
if (n_state == false) {
document.getElementById('newsteller').style.backgroundColor = "hsl(120, 3%, 93%)";
} else if (n_state == true) {
document.getElementById('newsteller').style.backgroundColor = "rgb(180, 223, 180)";
}
}
function blur_check(id) {
var element_base = document.getElementById(id);
var circleSibling = getCircle(element_base);
if (getComputedStyle(circleSibling).backgroundColor == "rgb(237, 238, 237)") {
circleSibling.style.backgroundColor = 'rgb(180, 223, 180)';
}
if (element_base.value == "") {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
function characters_check(sample) {
var arr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "#", ";", ":", "/", "+", ")", "&", "(", "?", "!", "-", "_", "%", "*", ":", ";", "`", "^", "$"]
for (var i = arr.length - 1; i >= 0; --i) {
if (sample.indexOf(arr[i]) != -1) {
return true;
}
}
}
function passwordBlur() {
var element = document.getElementById('mdpbis');
var circleSibling = getCircle(element);
if (getComputedStyle(circleSibling).backgroundColor == "rgb(237, 238, 237)") {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
function email_check() {
var circleSibling = getCircle(document.getElementById('email'));
var emailString = document.getElementById('email').value;
var arr = ["#"]
for (var i = arr.length - 1; i >= 0; --i) {
if (emailString.indexOf(arr[i]) != -1) {
var arr = ["."]
for (var i = arr.length - 1; i >= 0; --i) {
if (emailString.indexOf(arr[i]) != -1) {
circleSibling.style.backgroundColor = 'rgb(180, 223, 180)';
} else {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
} else {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
}
function getCircle(elements) {
while (elements = elements.nextSibling) {
if (elements.className === 'circle') {
return elements;
}
}
return false
}
function prenom_confirmation() {
var prenom = document.getElementById('prenom');
var circleStyle = getCircle(prenom).style;
if (characters_check(prenom.value) == true) {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
} else {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
}
}
function nom_confirmation() {
var nom = document.getElementById('nom');
var circleStyle = getCircle(nom).style;
if (characters_check(nom.value) == true) {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
} else {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
}
}
function username_confirmation() {
var username = document.getElementById('username');
var circleStyle = getCircle(username).style;
if (characters_check(username.value) == true) {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
} else {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
}
}
function email_confirmation() {
var email = document.getElementById('email');
var circleStyle = getCircle(email).style;
if (characters_check(email.value) == true) {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
} else {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
}
}
function mdp_confirmation() {
mdp_check()
var mdp = document.getElementById('mdp');
var circleStyle = getCircle(mdp).style;
if (characters_check(mdp.value) == true && mdp.value.length >= 6) {
circleStyle.backgroundColor = 'rgb(180, 223, 180)';
} else {
circleStyle.backgroundColor = '#FFE68D';
}
}
function mdp_check() {
var mdp = document.getElementById('mdp');
var circleMdp = getCircle(mdp);
var mdpbis = document.getElementById('mdpbis');
var circleMdpbis = getCircle(mdpbis);
if (mdpbis.value == mdp.value) {
circleMdpbis.style.backgroundColor = getComputedStyle(circleMdp).backgroundColor;
} else if (mdpbis.value !== mdp.value) {
circleMdpbis.style.backgroundColor = "rgb(237, 238, 237)";
}
}
* {
margin: 0px;
padding: 0px;
font-family: 'Futura', sans-serif;
-webkit-font-smoothing: anatialised;
}
::selection {
background: wheat;
}
a {
text-decoration: none;
}
body {
background: #DEDEDE;
}
input:focus,
select:focus {
outline: none;
}
.login-form-window {
margin-top: 50px;
width: 90%;
margin-left: 5%;
background: white;
display: block;
box-shadow: 1px 10px 40px 0px rgba(0, 0, 0, 0.10);
}
.window-header {
background: wheat;
color: hsl(120, 3%, 30%);
font-size: 28px;
padding: 10px;
font-weight: 100;
font-weight: 100;
}
.window-info {
padding: 10px;
color: hsl(120, 3%, 60%);
}
.description {
font-size: 19px;
color: hsl(120, 2%, 20%);
padding: 10px;
}
.input-des {
color: hsl(120, 3%, 35%);
margin: 10px;
}
.padding-right {
margin-right: 30px;
}
.form_col {
display: inline-block;
margin-right: 15px;
padding: 3px 0px;
width: 300px;
min-height: 1px;
text-align: right;
}
.text-input {
border: none;
background: hsl(120, 3%, 93%);
width: 150px;
height: 30px;
border-radius: 5px;
padding-left: -2px;
font-size: 15px;
text-align: center;
text-decoration: none;
}
.circle {
margin-left: 20px;
height: 30px;
width: 30px;
border-radius: 15px;
background-color: hsl(120, 3%, 93%);
vertical-align: bottom;
}
.select-country {
height: 30px;
border: none;
background: hsl(120, 3%, 93%);
font-size: 15px;
}
.checkbox {
width: 22px;
height: 22px;
border: none;
background: rgb(180, 223, 180);
border-radius: 4px;
vertical-align: sub;
}
.checkbox,
.submit-button {
cursor: pointer;
}
.submit-button {
padding: 3px 0px;
display: inline-block;
margin-right: 15px;
width: 300px;
border-radius: 5px;
text-align: center;
width: 200px;
background-color: hsl(120, 3%, 93%);
font-size: 19px;
color: hsl(120, 3%, 30%);
}
.submit-button::selection {
background: none;
}
#text::selection {
background: none;
}
<section class="login-form-window">
<p class="window-header">CREER UN COMPTE</p>
<p class="window-info"><a>Samedi 5 Mai</a><a style="float:right">Formulaire d'Inscription</a></p><br>
<form id="form">
<label class="description form_col" id="sex">Sexe:</label>
<input type="radio" name="sex" value="H" class="radio-input" checked="1"><label class="input-des padding-right">Homme</label>
<input type="radio" name="sex" value="F" class="radio-input"><label class="input-des padding-right">Femme</label>
<input type="radio" name="sex" value="O" class="radio-input"><label class="input-des">Autre</label><br><br>
<label class="description form_col">Prénom:</label>
<input id="prenom" type="text" name="prenom" value="" oninput="prenom_confirmation()" class="text-input prenom" autocomplete="given-name" onblur="blur_check('prenom')">
<canvas class="circle"></canvas>
<br><br>
<label class="description form_col">Nom:</label>
<input id="nom" type="text" name="nom" value="" oninput="nom_confirmation()" class="text-input nom" autocomplete="name" onblur="blur_check('nom')">
<canvas class="circle" id="nom"></canvas>
<br><br>
<label class="description form_col">Username:</label>
<input id="username" type="text" name="username" value="" oninput="username_confirmation()" class="text-input username" autocomplete="username" onblur="blur_check('username')">
<canvas class="circle" id="username"></canvas>
<br><br>
<label class="description form_col">Email:</label>
<input id="email" type="text" name="email" value="" class="text-input email" autocomplete="name" onblur=" email_check()" style="width:200px;">
<canvas class="circle" id="email"></canvas>
<br><br>
<label class="description form_col">Mot de passe:</label>
<input id="mdp" type="password" name="mdp" value="" oninput="mdp_confirmation()" class="text-input mdp" autocomplete="new-password" onblur="blur_check('mdp')">
<canvas class="circle" id="mdp"></canvas>
<br><br>
<label class="description form_col">Mot de passe (confirmation):</label>
<input id="mdpbis" type="password" name="mdpbis" value="" class="text-input mdpbis" autocomplete="new-password" oninput="mdp_check()" onblur="passwordBlur()">
<canvas class="circle" id="mdp-bis"></canvas>
<br><br>
<label class="description form_col">Pays de résidence:</label>
<select class="select-country" name="country">
<option value="">France</option>
<option value="">Belgique</option>
<option value="">Suisse</option>
<option value="">Luxembourg</option>
<option value="">États Unis</option>
<option value="">Allemagne</option>
<option value="">Pays-Bas</option>
<option value="">Norvège</option>
</select>
<br><br>
<label class="description form_col">Newsteller:</label>
<canvas class="checkbox" id="newsteller" onclick="toggleNewsteller()"></canvas><br><br>
<label class="description form_col"></label>
<div class="form_col submit-button" id="newsteller" onclick="">SUBMIT</div>
<br><br>
</form>
</section>

Just loop through each circle and check it's background-color value like this:
var x = document.querySelectorAll('.circle'); // get all circle elements
var y="";
x.forEach(circ => { //loop through each circle to check bg-color
if (circ.style.backgroundColor !== 'rgb(180, 223, 180)') {
y += '0';
} else {
y += '1';
}
});
if ( y.indexOf("0") > -1 ) { // are there red circles?
console.log('dont do anything'); //yes there are
} else {
console.log('run submit button css change function'); // no there aren't. go ahead and run a function to change submit css here
}
However, as #TemaniAfif mentioned, I would suggest you add the background-color for green to a css class say, green and red then toggle them like this:
if (emailString.indexOf(arr[i]) != -1) {
circleSibling.classList.add('green');
circleSibling.classList.remove('red');
} else {
circleSibling.classList.add('red');
circleSibling.classList.remove('green');
}
And replace the first snippet above with this:
var x = document.querySelectorAll('.circle'); // get all circle elements
x.forEach(circ => { //loop through each circle to check bg-color
if (circ.classList.contains('green')) {
y += '1';
} else {
y += '0';
}
});
if ( y.indexOf("0") > -1 ) { // are there red circles?
console.log('dont do anything'); //yes there are
} else {
console.log('run submit button css change function'); // no there aren't. go ahead and run a function to change submit css here
}
Toggling css classes instead of inline styles is cleaner and shorter too if you have a lot of circles which results in better site performance.

Related

How to remove the last child from a certain div of a div

I'm crawling the last steps towards a project assigned for one of my classes. Basically, I have to create an implementation on web of the NIM game only using HTML/CCS/JavaScript. Tomorrow's the deadline and I'm almost done, I just have an error on when I want the AI to remove a certain quantity of elements from a pile, it just says that the pile which I'm referring is undefined, even though when i debug the code it appears to have the right info. The game board is generated dynamically based on a width variable(w) and it is created in a function at the start of the game.
I'll snippet the whole project but basically I'm gonna highlight the functions of the creation of the board (working perfectly) and where I'm having some issues on removing elements. Thanks in advance for any possible help, it's my first frontend project experience and I'm tired and clueless on what to do...
game = document.getElementsByClassName("board");
let num = document.querySelector('#board_width');
// Handle number changes
w = num.valueAsNumber;
num.addEventListener('input', function () {
let val = num.valueAsNumber;
w = val;
//console.log(typeof val, val);
});
var msz=2*w-1;
for(let k=1; k<=w; k++){
let row = document.createElement("div");
row.className = "inner_game_piece";
for(let l=1; l<=maxcols; l++){
let elem = document.createElement("div");
elem.className = "game_piece";
elem.onclick = function(){
if(canclk[k]==1){
player_move(k);
row.removeChild(row.lastElementChild);
if(winCheck()) checkmate("P");
}
}
row.appendChild(elem);
}
game[0].appendChild(row);
maxcols+=2;
}
var gm = game[0].getElementsByTagName("div");
for(let i=1; i<gm.length; i++){
if(i==pile){
var rw = gm[i].getElementsByTagName("div");
for(let j=1; j<=qnt; j++){
el[pile]--;
//having some issues here
rw.removeChild(rw.lastElementChild);
}
break;
}
}
if(winCheck()) checkmate("C");
function openLog() {
document.getElementById('logNav').style.display = 'block';
}
function closeLog() {
document.getElementById('logNav').style.display = 'none';
}
function openRules() {
document.getElementById('ruleNav').style.display = 'block';
}
function closeRules() {
document.getElementById('ruleNav').style.display = 'none';
}
var w, difficulty = 4, el = new Array(), game, execnt=0, maxcols, canclk = new Array();
window.addEventListener('load',() => {
game = document.getElementsByClassName("board");
let num = document.querySelector('#board_width');
// Handle number changes
w = num.valueAsNumber;
num.addEventListener('input', function () {
let val = num.valueAsNumber;
w = val;
//console.log(typeof val, val);
});
el[0] = 0; canclk[0] = 0;
if(w>=4) maxcols=1;
else maxcols=5;
for(let i=1; i<=w; i++){
el[i]=maxcols+i*2-2;
canclk[i]=1;
}
if(execnt==0){
var msz=2*w-1;
for(let k=1; k<=w; k++){
let row = document.createElement("div");
row.className = "inner_game_piece";
for(let l=1; l<=maxcols; l++){
let elem = document.createElement("div");
elem.className = "game_piece";
elem.onclick = function(){
if(canclk[k]==1){
player_move(k);
row.removeChild(row.lastElementChild);
if(winCheck()) checkmate("P");
}
}
row.appendChild(elem);
}
game[0].appendChild(row);
maxcols+=2;
}
execnt++;
}
});
function disenabler(pile){
for(let i=1; i<=w; i++){
if(pile==-1) canclk[i]=-1;
if(canclk[i]==2) canclk[i]--;
if(i!=pile && canclk[i]!=0 && pile!=0) canclk[i]=2;
}
}
function player_move(pile) {
if(canclk[pile]==1){
el[pile]--;
if(el[pile]==0) canclk[pile] = 0;
disenabler(pile);
if(winCheck()) checkmate("P");
}
}
function endOfTurn(){
disenabler(-1);
ai_move();
disenabler(0);
}
function winCheck(){
var activelems=0;
for(let i=1; i<=w; i++){activelems += el[i] }
console.log(activelems);
if(activelems==0) return true;
else return false;
}
function ai_move(){
if(winCheck()) checkmate("P");
var chance = document.querySelector('input[name="diff"]:checked').value;
var rn = Math.floor(Math.random() * 10) + 1;
if(rn>chance) random_play();
else winner_move();
}
function isWinning(){
var an = el[i], or = el[i], res;
if(w>1){
for(let i=2; i<=w; i++){
an = (an ^ el[i])==0;
or = (or | el[i+1])==1;
}
res = an^or;
}
else res = (an==0) ^ (or==1);
return res;
}
function random_play(){
var pile = 0, qnt=0;
while(el[pile]==0){
pile = Math.floor(Math.random() * w) + 1;
}
qnt = Math.floor(Math.random() * el[pile]) + 1;
var gm = game[0].getElementsByTagName("div");
for(let i=1; i<gm.length; i++){
if(i==pile){
var rw = gm[i].getElementsByTagName("div");
for(let j=1; j<=qnt; j++){
el[pile]--;
//having some issues here
rw.removeChild(rw.lastElementChild);
}
break;
}
}
if(winCheck()) checkmate("C");
}
function dec2bin(dec) {
var st = ((dec >>> 0).toString(2)).split("").reverse().join("");
console.log(dec, st);
return dec;
}
function winner_move(){
var pile=2, quantity=2, flag=0, counter=0;
var pair = new Array();
var pieces = new Array();
for(let i=1; i<=w; i++){
if(el[i]==0) continue;
pieces = dec2bin(el[i]);
for(let j=0; j<pieces.length; j++){
var v = pieces.charCodeAt(j)-48; var op=0;
if(v==1){
if(pair[j]%2==0){
flag = i;
counter += Math.pow(2,j);
} else{
flag = 0;
counter -= Math.pow(2,j);
}
}
pair[j]++;
}
}
pile=flag; quantity=counter;
if(quantity==0) random_play();
var gm = game[0].getElementsByTagName("div");
for(let i=1; i<gm.length; i++){
if(i==pile){
var rw = gm[i].getElementsByTagName("div");
for(let j=1; j<=quantity; j++){
el[pile]--;
rw.removeChild(rw.lastElementChild);
}
break;
}
}
if(winCheck()) checkmate("C");
}
function checkmate(winner){
if(winner=="P"){
//update win count on leaderboard table
alert("YOU WON, CONGRATULATIONS!!");
}
if(winner=="C"){
alert("Sorry, you lost :(");
}
document.location.reload();
}
body {
background-color: rgba(131, 128, 135, 1);
color: rgba(233, 255, 255, 1);
font-family: Montserrat;
overflow: auto;
}
input[type=number] {
width: 40px;
}
input[type=submit], input[type=number],
button[type=submit], button[type=button] {
background-color: rgba(131, 128, 135, 1);
color: rgba(233, 255, 255, 1);
border: none;
border-radius: 5px;
padding-top: 3px;
padding-bottom: 3px;
}
input[type=submit]:hover, button[type=submit]:hover{
color: rgba(77, 254, 209, 1);
transition: 0.5s;
}
input[type=text], input[type=password]{
background-color: rgba(51, 60, 74, 1);
color: rgba(233, 255, 255, 1);
border: 2px solid rgba(77, 254, 209, 1);
border-radius: 5px;
width: 80%;
padding: 10px 10px;
margin: 12px 0;
box-sizing: border-box;
}
h1 {
padding-left: 2%;
}
h2 {
font-size: 25px;
color: rgba(77, 254, 209, 1);
}
p {
text-align: justify;
padding-left: 3%;
}
ul{
text-align: left;
}
.white_hr {
width: 50%;
align-self: center;
border-top: 5px solid rgba(233, 255, 255, 1);;
border-radius: 5px;
}
.highlight {
color:rgba(77, 254, 209, 1);
font-weight: bold;
font-style: italic;
}
.header {
background-color: rgba(51, 60, 74, 1);
border-radius: 30px;
height: 60px;
width: auto;
position: relative;
}
.header h1 {
font-size: 30px;
float: left;
padding-left: 20px;
position: absolute;
top: 50%;
margin-top: -16px;
}
.header h3 {
color: rgba(77, 254, 209, 1);
float: right;
padding-right: 20px;
}
.header h3:hover {
transition: 0.5s;
color: rgba(233, 255, 255, 1);
cursor: pointer;
}
.container {
text-align: center;
height: 700px;
width: 98%;
display: flex;
justify-content: space-between;
padding-top: 2%;
padding-right: 5px;
padding-left: 5px;
padding-bottom: 30px;
}
.container hr {
width: 80%;
border-top: 5px solid rgba(77, 254, 209, 1);
border-radius: 5px;
}
.container h2:hover {
transition: 0.5s;
color: rgba(233, 255, 255, 1);
cursor: pointer;
}
.container div {
align-items: center;
padding-top: 1%;
}
.inner_game_piece {
display: flex;
flex-direction: row;
align-items: center;
justify-content: left;
max-width: 750px;
margin: 0 auto;
flex-wrap: wrap;
}
.game_piece{
width:45px;
height:35px;
border-radius: 50px;
margin:5px;
background-color: rgba(51, 60, 74, 1);
}
.settings, .game, .leaderboard {
display: inline-block;
vertical-align: top;
}
.settings, .leaderboard {
background-color: rgba(51, 60, 74, 1);
border-radius: 20px;
height: auto;
width: 20%;
}
.game {
border: 5px solid rgba(51, 60, 74, 1);
border-radius: 20px;
height: auto;
width: 55%;
}
.small_size {
font-size: 16px;
font-weight: bold;
color: rgba(229, 202, 202, 1);
}
.logNav, .ruleNav {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(131, 128, 135, 1);
background-color: rgba(131, 128, 135, 0.5);
padding: 20% 0 0 0;
}
.log_container, .rule_container{
background-color: rgba(51, 60, 74, 1);
margin: 5% auto 15% auto;
border: none;
border-radius: 10px;
width: 80%;
height: auto;
padding: 2% 2% 2% 0;
}
.closex {
float: right;
color: rgba(77, 254, 209, 1);
font-weight: bold;
font-size: 30px;
cursor: pointer;
}
.closex:hover {
transition: 0.5s;
color: rgba(233, 255, 255, 1);
}
.cancelbtn {
margin: 10px 0;
width: auto;
height: auto;
padding: 80% 10px;
}
.about_title, .rule_title {
font-size: 30px;
text-align: left;
color:rgba(77, 254, 209, 1);
}
.logs {
background-color: rgba(51, 60, 74, 1);
border-radius: 15px;
width: 100%;
height: 150px;
}
.logs h4 {
font-size: 20px;
color: rgba(77, 254, 209, 1);
padding: 2% 2% 0 2%;
}
.logs_box {
background-color:rgba(131, 128, 135, 0.5);
overflow: auto;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width:device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
<title>N I M</title>
</head>
<body>
<div class="header">
<h1>N I M</h1>
<h3 onclick="openLog()">Log in</h3>
</div>
<!-- Login prompt-->
<div id="logNav" class="logNav">
<form>
<div class="log_container">
<div class="log_auth">
<span class="closex" onclick="closeLog()" title="close Login">×</span><br>
<label for="username"><b>Username</b></label><br>
<input type="text" id="username" placeholder="Enter Username" name="username" required><br>
<label for="password"><b>Password</b></label><br>
<input type="password" id="password" placeholder="Enter Password" name="password" required><br>
<button type="submit">Login</button>
<label>
<input type="checkbox" name="guest"><b>Stay as guest</b>
</label><br>
</div>
</div>
</form>
</div>
<div id="main" class="main">
<div class="container">
<!-- Settings Tab -->
<div class="settings">
<h2>Settings</h2>
<hr>
<form>
<div>
<label for="board_width"><b>Board Size</b></label><br>
<input type="number" id="board_width" name="board_width" value="1">
</div>
<hr>
<div>
<h2>Game Mode</h2>
<label for="single_player" class="small_size">SinglePlayer</label>
<input type="radio" id="single_player" name="choose_mode"><br>
<label for="multi_player" class="small_size">MultiPlayer</label>
<input type="radio" id="multi_player" name="choose_mode"><br>
</div>
<hr>
<div>
<h2>Difficulty</h2>
<label for="easy_diff" class="small_size">Easy</label>
<input type="radio" id="easy_diff" value=1 name="diff"><br>
<label for="medium_diff" class="small_size">Medium</label>
<input type="radio" id="medium_diff" value=4 name="diff"><br>
<label for="hard_diff" class="small_size">Hard</label>
<input type="radio" id="hard_diff" value=8 name="diff"><br>
<label for="extreme_diff" class="small_size">Extreme</label>
<input type="radio" id="extreme_diff" value=10 name="diff"><br>
</div>
<hr>
<h2 onclick="openRules()">Rules/About</h2>
<div id="ruleNav" class="ruleNav">
<div class="rule_container">
<span class="closex" onclick="closeRules()" title="close Rules/About">×</span><br>
<h1 class="about_title"><u>What is the NIM game?</u></h1>
<p> -> Nim is a mathematical game of <span class="highlight">strategy</span> in which 2 players take turns
to remove objects from distinct piles. In each turn, the player must choose one pile
and remove at least 1 object from that pile. <b>To win the game you must be the last
player to remove the final set of objects!</b>
</p>
<h1 class="rule_title"><u>What are the Rules?</u></h1>
<ul>
<li>In each turn, the player must remove 1 or more object from an unique horizontal pile;</li>
<li>The player cannot remove 2 or more objects from different piles in the same turn;</li>
<li>Depending on the settings defined:</li>
<li style="list-style: none;"><ul>
<li>The amount of piles can be defined by the user;</li>
<li>The user can also choose who goes first (player 1 or player 2);</li>
<li>Game can be player online <b>(work in progress)</b> or with a robot;</li>
<li>If <b>SinglePlayer</b> was selected, the player can choose the desired difficulty;</li>
</ul></li>
<li>In case of a foul play, the game will not register the move, and will wait for a proper move;</li>
<li>Logs about the state of the game are shown below the game area <b>(for foul plays, winning, and play information)</b>;</li>
</ul>
</div>
</div>
</form>
</div>
<div class="game">
<h2>Game Board</h2>
<hr>
<div class="board"></div>
<script src="script.js"></script>
<hr>
<div class="game_btn">
<button type="reset" onClick="window.location.reload()">New Game / Reset</button>
<button type="button" onClick="endOfTurn()">End Turn</button>
</div>
</div>
<div class="leaderboard">
<h2>Leaderboards</h2>
<hr>
<div class="result_box">
<p>- theres no results registered adfsdfadfasdfsfd</p>
</div>
</div>
</div>
<div class="logs">
<h4>Logs</h4>
<div class="log_box">
<p>lobby: Welcome to NIM!</p>
</div>
</div>
</div>
</body>
</html>
Try to replace
var rw = gm[i].querySelector("div"); <=== changed
for(let j=1; j<=qnt; j++){
el[pile]--;
//having some issues here
rw.removeChild(rw.lastElementChild);
}
break;
getElementsByTagName returns HTMLCollection.
There is no method removeChild in HTMLCollection.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
Keep your code consistent - naming is 80% of coding (game and msz), 10% is consistency (winCheck and ai_move). The rest is describe in API's documentation ;)
Well done!

Problems making a button disabled/change color depending on the input. Any advice?

I've been tying to work on this code, but can't find the mistakes (and I'm guessing there are many of them) I'm making.
So far I tried it using querySelector and getElementById and I've been rewriting the functions quite a few times, but no luck so far. Any advice?
Thanks in advance.
const btnNext = document.querySelector(".btn-next");
const logIn = document.querySelector(".btn-login");
const inputMail = document.querySelector(".input-mail");
const inputPassword = document.querySelector(".input-password");
function btnLogIn() {
if (inputMail.value.length && inputPassword.value.length == 0) {
btnNext.disabled == true;
} else {
btnNext.disabled == false;
}
}
function changeColor() {
if (document.getElementById("input-mail") !== "") {
document.getElementById("btn-next").style.background = "gray";
} else {
document.getElementById("btn-next").style.background = "blue";
}
}
body{
margin: auto;
width:50%;
padding: 0;
background-color: #eeeeee;
}
form{
display: flex;
flex-direction: column;
}
.btn-next{
margin-top: .5rem;
background-color: #949aa6;
color: white;
border: none;
border-radius: 2px;
padding: 18px 119px 18px 119px;
font-size: .8rem;
font-weight: 600;
}
input{
width: 16.5rem;
height: 2rem;
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
}
<body>
<form>
<p>Email</p>
<input type="email" placeholder="Email" class="input-mail" id="input-mail" onkeyup="changeColor()">
<p>Password</p>
<input type="password" placeholder="Password" class="input-password" id="input-password"><br>
</form>
<button class="btn-next" id="btn-next">NEXT</button>
</body>
const btnNext = document.querySelector(".btn-next");
const logIn = document.querySelector(".btn-login");
const inputMail = document.querySelector(".input-mail");
const inputPassword = document.querySelector(".input-password");
inputMail.addEventListener("input", verifyInput);
inputPassword.addEventListener("input", verifyInput);
function verifyInput() {
if (
inputMail.value.trim().length == 0 ||
inputPassword.value.length == 0
) {
btnNext.disabled = true;
btnNext.style.backgroundColor = "gray";
} else {
btnNext.disabled = false;
btnNext.style.backgroundColor = "blue";
}
}
body{
margin: auto;
width:50%;
padding: 0;
background-color: #eeeeee;
}
form{
display: flex;
flex-direction: column;
}
.btn-next{
margin-top: .5rem;
background-color: #949aa6;
color: white;
border: none;
border-radius: 2px;
padding: 18px 119px 18px 119px;
font-size: .8rem;
font-weight: 600;
}
input{
width: 16.5rem;
height: 2rem;
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
}
<body>
<form>
<p>Email</p>
<input type="email" placeholder="Email" class="input-mail" id="input-mail">
<p>Password</p>
<input type="password" placeholder="Password" class="input-password" id="input-password"><br>
</form>
<button class="btn-next" id="btn-next" disabled>NEXT</button>
</body>
Change the following to
function btnLogIn() {
if (inputMail.value.length && inputPassword.value.length == 0) {
btnNext.disabled = true;
} else {
btnNext.disabled = false;
}
}
corrected '=' signs to change line from comparison to allocation.

Adding a square root function to a calc using js

So, I made a calculator, and I want to add a square root function, but I know there is no already made function that finds the square root of numbers. So what elements can I combine to find the square root of a number?
const screen = document.querySelector("#screen");
const clearButton = document.querySelector("#clear");
const equalsButton = document.querySelector("#equals");
const decimalButton = document.querySelector("#decimal");
let isFloat = false;
let signOn = false;
let firstNumber = "";
let operator = "";
let secondNumber = "";
let result = "";
const allClear = () => {
isFloat = false;
signOn = false;
firstNumber = "";
operator = "";
secondNumber = "";
result = "";
screen.value = "0";
};
const calculate = () => {
if (operator && result === "" && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
secondNumber = screen.value.substring(firstNumber.length + 3);
switch (operator) {
case "+":
result = Number((Number(firstNumber) + Number(secondNumber)).toFixed(3));
break;
case "-":
result = Number((Number(firstNumber) - Number(secondNumber)).toFixed(3));
break;
case "*":
result = Number((Number(firstNumber) * Number(secondNumber)).toFixed(3));
break;
case "/":
result = Number((Number(firstNumber) / Number(secondNumber)).toFixed(3));
break;
default:
}
screen.value = result;
}
};
clear.addEventListener("click", allClear);
document.querySelectorAll(".number").forEach((numberButton) => {
numberButton.addEventListener("click", () => {
if (screen.value === "0") {
screen.value = numberButton.textContent;
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent === "0") {
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent !== "0") {
screen.value = screen.value.substring(0, screen.value.length - 1) + numberButton.textContent;
} else if (result || result === 0) {
allClear();
screen.value = numberButton.textContent;
} else {
screen.value += numberButton.textContent;
}
});
});
decimalButton.addEventListener("click", () => {
if (result || result === 0) {
allClear();
isFloat = true;
screen.value += ".";
} else if (!isFloat) {
isFloat = true;
if ([" ", "+", "-"].includes(screen.value[screen.value.length - 1])) {
screen.value += "0.";
} else {
screen.value += ".";
}
}
});
document.querySelectorAll(".operator").forEach((operatorButton) => {
operatorButton.addEventListener("click", () => {
if (result || result === 0) {
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (operator && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
calculate();
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (!operator) {
isFloat = false;
firstNumber = screen.value;
operator = operatorButton.dataset.operator;
screen.value += ` ${operatorButton.textContent} `;
} else if (!signOn
&& !["*", "/"].includes(operatorButton.dataset.operator)
&& screen.value[screen.value.length - 1] === " ") {
signOn = true;
screen.value += operatorButton.textContent;
}
});
});
equalsButton.addEventListener("click", calculate);
* {
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
font-weight: 300;
margin: 0;
padding: 0;
}
body {
background-color: #222;
height: 100vh;
}
header {
background-color: #333;
padding: 40px 0;
}
header h1 {
-webkit-background-clip: text;
background-clip: text;
background-image: linear-gradient(to right bottom, #fff, #777);
color: transparent;
font-size: 40px;
letter-spacing: 2px;
text-align: center;
text-transform: uppercase;
}
main {
background-color: #222;
display: flex;
justify-content: center;
padding: 60px 0;
}
main #container {
background-color: #333;
box-shadow: 0 5px 5px #111;
padding: 20px;
}
.clearfix:after {
clear: both;
content: " ";
display: block;
font-size: 0;
height: 0;
visibility: hidden;
}
#container .row:not(:last-child) {
margin-bottom: 9px;
}
#container input,
#container button {
float: left;
}
#container input:focus,
#container button:focus {
outline: none;
}
#container input {
background-color: #222;
border: 1px solid #999;
border-right-width: 0;
color: #999;
font-size: 22px;
font-weight: 300;
height: 80px;
padding-right: 14px;
text-align: right;
width: 261px;
}
#container button {
background-color: #222;
border: none;
box-shadow: 0 3px 0 #111;
color: #999;
font-size: 20px;
height: 80px;
margin-right: 7px;
width: 80px;
}
#container button:active {
box-shadow: 0 2px 0 #111;
transform: translateY(1px);
}
#container #clear,
#container .operator,
#container #equals {
color: #111;
}
#container #clear,
#container .operator {
margin-right: 0;
}
#container #clear {
background-color: #e95a4b;
border: 1px solid #999;
border-left-width: 0;
box-shadow: none;
cursor: pointer;
}
#container #clear:active {
box-shadow: none;
transform: none;
}
#container .operator {
background-color: #999;
box-shadow: 0 3px 0 #555;
}
#container .operator:active {
box-shadow: 0 2px 0 #555;
}
#container #equals {
background-color: #2ecc71;
box-shadow: 0 3px 0 #155d34;
}
#container #equals:active {
box-shadow: 0 2px 0 #155d34;
}
#media only screen and (max-width: 400px) {
header {
padding: 28px 0;
}
header h1 {
font-size: 36px;
}
main {
padding: 40px 0;
}
main #container {
padding: 16px;
}
#container .row:not(:last-child) {
margin-bottom: 7px;
}
#container input {
font-size: 18px;
height: 60px;
padding-right: 10px;
width: 195px;
}
#container button {
font-size: 16px;
height: 60px;
margin-right: 5px;
width: 60px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">
<link href="Project 1.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Calculator</h1>
</header>
<main>
<div id="container">
<div class="row clearfix">
<input id="screen" value="0" disabled type="text">
<button id="clear">AC</button>
</div>
<div class="row clearfix">
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button data-operator="+" class="operator">+</button>
</div>
<div class="row clearfix">
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button data-operator="-" class="operator">-</button>
</div>
<div class="row clearfix">
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button data-operator="*" class="operator">×</button>
</div>
<div class="row clearfix">
<button id="decimal">.</button>
<button class="number">0</button>
<button id="equals">=</button>
<button data-operator="/" class="operator">÷</button>
</div>
</div>
</main>
<script src="Project 1.js"></script>
</body>
</html>
This is the code for the calc.. Feel free to edit it and explain to me what you did.
There is already one.
The Math.sqrt() function returns the square root of a number, that is, ∀x≥0,Math.sqrt(x)=x
=the uniquey≥0such thaty2=x
MDN Docs
You can use javascript built in
Math.sqrt(number)

Javascript - NaN.undefined as textholder problem

I have got a problem at the coding project I am doing, as I formatted the numbers to be shown nicer, I ran into a problem. The webpage when it loads shows NaN. undefined in the total income/expenses at the top. I can't figure out what is the problem.
//Budget controller
var budgetController = (function() {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
};
Expense.prototype.calcPercentage = function(totalIncome) {
if (totalIncome > 0) {
this.percentage = Math.round((this.value / totalIncome) * 100);
} else {
this.percentage = -1;
}
};
Expense.prototype.getPercentage = function() {
return this.percentage;
};
var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
var calculateTotal = function(type) {
var sum = 0;
data.allItems[type].forEach(function(cur) {
sum = sum + cur.value;
});
data.totals[type] = sum;
};
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
return {
addItem: function(type, des, val) {
var newItem, ID;
//create new iD
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
//CREATe new item, if it is inc or exp
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// Push all items into data structure and return the new element
data.allItems[type].push(newItem);
return newItem;
},
deleteItem: function(type, id) {
var ids, index;
ids = data.allItems[type].map(function(current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function() {
// calculate the total income and expenses
calculateTotal('exp');
calculateTotal('inc');
// calculate the budget: income - expenses
data.budget = data.totals.inc - data.totals.exp;
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
} else {
data.percentage = -1;
}
},
calculatePercentages: function() {
data.allItems.exp.forEach(function(cur) {
cur.calcPercentage(data.totals.inc);
});
},
getPercentages: function() {
var allPerc = data.allItems.exp.map(function(cur) {
return cur.getPercentage();
});
return allPerc;
},
getBudget: function() {
return {
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage
};
}
};
})();
// UI Controller
var UIController = (function() {
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expensesLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
container: '.container',
expensesPercLabel: '.item__percentage',
dateLabel: '.budget__title--month'
};
var formatNumber = function(num, type) {
var numSplit, int, dec, type;
/* + or - befofe a number
on 2 decimals
comma seperating thousands
*/
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510
}
dec = numSplit[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
};
var nodeListForEach = function(list, callback) {
for (var i = 0; i < list.length; i++) {
callback(list[i], i);
}
};
return {
getInput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value, //will be either inc or exp
description: document.querySelector(DOMstrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMstrings.inputValue).value)
};
},
addListItem: function(obj, type) {
var html, newHtml, element;
// Create HTML string with placeholder text
if (type === 'inc') {
element = DOMstrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"> <div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
} else if (type === 'exp') {
element = DOMstrings.expensesContainer;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
}
// Replace the placeholder text with some actual data
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', formatNumber(obj.value, type));
// Insert the HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteListItem: function(selectorID) {
var el = document.getElementById(selectorID);
el.parentNode.removeChild(el);
},
clearFields: function() {
var fields, fieldsArr;
fields = document.querySelectorAll(
DOMstrings.inputDescription + ',' + DOMstrings.inputValue
);
fieldsArr = Array.prototype.slice.call(fields);
fieldsArr.forEach(function(current, index, array) {
current.value = "";
});
fieldsArr[0].focus();
},
displayBudget: function(obj) {
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';
document.querySelector(DOMstrings.budgetLabel).textContent = formatNumber(obj.budget, type);
document.querySelector(DOMstrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc');
document.querySelector(DOMstrings.expensesLabel).textContent = formatNumber(obj.totalExp, 'exp');
if (obj.percentage > 0) {
document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMstrings.percentageLabel).textContent = '---';
}
},
displayPercentages: function(percentages) {
var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);
nodeListForEach(fields, function(current, index) {
if (percentages[index] > 0) {
current.textContent = percentages[index] + '%';
} else {
current.textContent = '---';
}
});
},
getDOMstrings: function() {
return DOMstrings;
}
};
})();
// App Controller - global
var controller = (function(budgetCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem);
};
var updateBudget = function() {
// 1. Calculate the budget
budgetCtrl.calculateBudget();
// 2. Return the budget
var budget = budgetCtrl.getBudget();
// 3. Display the budget on the UI
UICtrl.displayBudget(budget);
};
var updatePercentages = function() {
// 1. Calculate percentages
budgetCtrl.calculatePercentages();
// 2. Read percentages from the budget controller
var percentages = budgetCtrl.getPercentages();
// 3. Update the UI with the new percentages
UICtrl.displayPercentages(percentages);
};
var ctrlAddItem = function() {
var input, newItem;
// 1. Get the field input data
input = UICtrl.getInput();
if (input.description !== "" && !isNaN(input.value) && input.value > 0) {
// 2. Add the item to the budget controller
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. Add the item to the UI
UICtrl.addListItem(newItem, input.type);
// 4. Clear the fields
UICtrl.clearFields();
// 5. Calculate and update budget
updateBudget();
// 6. Calculate and update percentages
updatePercentages();
}
};
var ctrlDeleteItem = function(event) {
var itemID, splitID, type, ID;
itemID = event.target.parentNode.parentNode.parentNode.parentNode.id;
if (itemID) {
//inc-1
splitID = itemID.split('-');
type = splitID[0];
ID = parseInt(splitID[1]);
// 1. delete the item from the data structure
budgetCtrl.deleteItem(type, ID);
// 2. Delete the item from the UI
UICtrl.deleteListItem(itemID);
// 3. Update and show the new budget
updateBudget();
// 4. Calculate and update percentages
updatePercentages();
}
};
return {
init: function() {
console.log('App has started');
UICtrl.displayBudget({
budget: 0,
totalIncome: 0,
totalExpenses: 0,
percentage: -1
});
setupEventListeners();
}
};
})(budgetController, UIController);
controller.init();
/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
color: #555;
font-family: Open Sans;
font-size: 16px;
position: relative;
height: 100vh;
font-weight: 400;
}
.right {
float: right;
}
.red {
color: #FF5049 !important;
}
.red-focus:focus {
border: 1px solid #FF5049 !important;
}
/**********************************************
*** TOP PART
**********************************************/
.top {
height: 40vh;
background-image: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url(back.png);
background-size: cover;
background-position: center;
position: relative;
}
.budget {
position: absolute;
width: 350px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
}
.budget__title {
font-size: 18px;
text-align: center;
margin-bottom: 10px;
font-weight: 300;
}
.budget__value {
font-weight: 300;
font-size: 46px;
text-align: center;
margin-bottom: 25px;
letter-spacing: 2px;
}
.budget__income,
.budget__expenses {
padding: 12px;
text-transform: uppercase;
}
.budget__income {
margin-bottom: 10px;
background-color: #28B9B5;
}
.budget__expenses {
background-color: #FF5049;
}
.budget__income--text,
.budget__expenses--text {
float: left;
font-size: 13px;
color: #444;
margin-top: 2px;
}
.budget__income--value,
.budget__expenses--value {
letter-spacing: 1px;
float: left;
}
.budget__income--percentage,
.budget__expenses--percentage {
float: left;
width: 34px;
font-size: 11px;
padding: 3px 0;
margin-left: 10px;
}
.budget__expenses--percentage {
background-color: rgba(255, 255, 255, 0.2);
text-align: center;
border-radius: 3px;
}
/**********************************************
*** BOTTOM PART
**********************************************/
/***** FORM *****/
.add {
padding: 14px;
border-bottom: 1px solid #e7e7e7;
background-color: #f7f7f7;
}
.add__container {
margin: 0 auto;
text-align: center;
}
.add__type {
width: 55px;
border: 1px solid #e7e7e7;
height: 44px;
font-size: 18px;
color: inherit;
background-color: #fff;
margin-right: 10px;
font-weight: 300;
transition: border 0.3s;
}
.add__description,
.add__value {
border: 1px solid #e7e7e7;
background-color: #fff;
color: inherit;
font-family: inherit;
font-size: 14px;
padding: 12px 15px;
margin-right: 10px;
border-radius: 5px;
transition: border 0.3s;
}
.add__description {
width: 400px;
}
.add__value {
width: 100px;
}
.add__btn {
font-size: 35px;
background: none;
border: none;
color: #28B9B5;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1.1;
margin-left: 10px;
}
.add__btn:active {
transform: translateY(2px);
}
.add__type:focus,
.add__description:focus,
.add__value:focus {
outline: none;
border: 1px solid #28B9B5;
}
.add__btn:focus {
outline: none;
}
/***** LISTS *****/
.container {
width: 1000px;
margin: 60px auto;
}
.income {
float: left;
width: 475px;
margin-right: 50px;
}
.expenses {
float: left;
width: 475px;
}
h2 {
text-transform: uppercase;
font-size: 18px;
font-weight: 400;
margin-bottom: 15px;
}
.icome__title {
color: #28B9B5;
}
.expenses__title {
color: #FF5049;
}
.item {
padding: 13px;
border-bottom: 1px solid #e7e7e7;
}
.item:first-child {
border-top: 1px solid #e7e7e7;
}
.item:nth-child(even) {
background-color: #f7f7f7;
}
.item__description {
float: left;
}
.item__value {
float: left;
transition: transform 0.3s;
}
.item__percentage {
float: left;
margin-left: 20px;
transition: transform 0.3s;
font-size: 11px;
background-color: #FFDAD9;
padding: 3px;
border-radius: 3px;
width: 32px;
text-align: center;
}
.income .item__value,
.income .item__delete--btn {
color: #28B9B5;
}
.expenses .item__value,
.expenses .item__percentage,
.expenses .item__delete--btn {
color: #FF5049;
}
.item__delete {
float: left;
}
.item__delete--btn {
font-size: 22px;
background: none;
border: none;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1;
display: none;
}
.item__delete--btn:focus {
outline: none;
}
.item__delete--btn:active {
transform: translateY(2px);
}
.item:hover .item__delete--btn {
display: block;
}
.item:hover .item__value {
transform: translateX(-20px);
}
.item:hover .item__percentage {
transform: translateX(-20px);
}
.unpaid {
background-color: #FFDAD9 !important;
cursor: pointer;
color: #FF5049;
}
.unpaid .item__percentage {
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
}
.unpaid:hover .item__description {
font-weight: 900;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:100,300,400,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Budgety</title>
</head>
<body>
<div class="top">
<div class="budget">
<div class="budget__title">
Available Budget in <span class="budget__title--month">%Month%</span>:
</div>
<div class="budget__value">+ 2,345.64</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 4,300.00</div>
<div class="budget__income--percentage"> </div>
</div>
</div>
<div class="budget__expenses clearfix">
<div class="budget__expenses--text">Expenses</div>
<div class="right clearfix">
<div class="budget__expenses--value">- 1,954.36</div>
<div class="budget__expenses--percentage">45%</div>
</div>
</div>
</div>
</div>
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
<div class="container clearfix">
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!--
<div class="item clearfix" id="income-0">
<div class="item__description">Salary</div>
<div class="right clearfix">
<div class="item__value">+ 2,100.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
The problem is that in the function formatNumber, the value num is not initialized at first time. For solving this, you can put a default value when the value of num is empty, like this:
var formatNumber = function(num = 0, type = '') {
var numSplit, int, dec, type;
/* + or - befofe a number
on 2 decimals
comma seperating thousands
*/
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510
}
dec = numSplit[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
};

character selction option for the players in tic-tac-toe

i have made a tic-tac-toe game.For which i have to make a character selection module for each player.Players have to choose between x and o.If first one selects 'o' ,other player can not select that.he has to choose 'x'.But including html lines ,the code i have written is almost 50 lines and very fragile, i can't find any other way to shorten this code.selection option is a basic thing in games.Any expert solution on this matter would be appreciated
function Player(name,val){
this.name=name;
this.val=val;
}
var ps=document.getElementById('ps');
ps.addEventListener('click',function(e){
player1=prompt('input player1');
char1=prompt('input char between x/o');
if((char1 != 'x') && (char1 != 'o')){
for(;;){
alert('select between x an o please');
char1=prompt('between x/o');
if((char1 === 'x')|| (char1 === 'o')){
break;
}
}
}
player2 = prompt('input player2');
char2 = prompt('input your char O/X');
if((char2 === char1) || ((char2 != 'x') && (char2 != 'o'))){
for(;;){
alert('you can not have this char');
char2=prompt('try again');
if(((char2 === 'o') || (char2 === 'x')) && (char2 != char1)){
break;
}
}
}
p1=new Player(player1,char1);
p2=new Player(player2,char2);
document.body.innerHTML+='\n'+p1.name+' : '+p1.val+'\n'+p2.name+' : '+p2.val;
});
<input type='button' value='Player Setup' id='ps'>
Instead of using prompt, its better to make use of HTML <input> elements.
Demo on Fiddle
HTML:
<div class="container">
<div class="p1">
<label>Player 1:</label>
<input id="p1" type="text" />
<br />
<br />
<label>Choose your Character:</label>
<br />
<input class="charac" type="radio" name="characP1" value="X" />
<label class="charac">X</label>
<br />
<input class="charac" type="radio" name="characP1" value="O" />
<label class="charac">O</label>
</div>
<div class="p2">
<label>Player 2:</label>
<input id="p2" type="text" />
<br />
<br />
<label>Choose your Character:</label>
<br />
<input class="charac cp2" type="radio" name="characP2" value="X" />
<label class="charac">X</label>
<br />
<input class="charac cp2" type="radio" name="characP2" value="O" />
<label class="charac">O</label>
</div>
<div class="btnContainer">
<input id="btn" class="btn" type="button" value="Submit" />
</div>
<div id="message"></div>
</div>
JavaScript:
var ps = document.getElementById('btn');
var c1 = document.getElementsByName('characP1');
var c2 = document.getElementsByName('characP2');
var msg = document.getElementById('message');
var char1;
var char2;
function Player(name, val) {
this.name = name;
this.val = val;
}
for (i = 0; i < c1.length; i++) {
c1[i].addEventListener('change', function () {
if (this.checked) {
this.value == 'X' ? c2[1].checked = true : c2[0].checked = true;
char1 = this.value;
char2 = this.value == 'X' ? 'O' : 'X';
}
});
}
for (i = 0; i < c2.length; i++) {
c2[i].addEventListener('change', function () {
if (this.checked) {
this.value == 'X' ? c1[1].checked = true : c1[0].checked = true;
char2 = this.value
char1 = this.value == 'X' ? 'O' : 'X';
}
});
}
ps.addEventListener('click', function () {
var player1 = document.getElementById('p1').value;
var player2 = document.getElementById('p2').value;
p1 = new Player(player1, char1);
p2 = new Player(player2, char2);
if (p1.name && p1.val && p2.name && p2.val) {
msg.innerHTML = p1.name + ' : ' + p1.val + '<br />' + p2.name + ' : ' + p2.val;
} else {
msg.innerHTML = 'Please fill all input fields'
}
});
CSS:
.charac {
position: relative;
left: 0px;
}
.container {
width: 250px;
margin: 0 auto;
}
.p1, .p2, #message {
width: 100%;
height: 100%;
border: 4px solid #51634b;
border-radius: 10px;
padding: 10px;
margin: 10px;
}
#message {
text-align: center;
border: none;
}
.btnContainer {
padding: 10px;
margin-left: 40px;
}
input.charac {
position: relative;
top: 3px;
}
input[type=text] {
height: 25px;
background: transparent;
border-radius: 6px;
outline: none;
color: #51634b;
font-size: 12px;
border: 1px solid #51634b;
margin-left: 5px;
padding: 2px;
text-align: center;
}
input[type=text]:focus {
box-shadow: 0px 0px 4px #62745c;
}
input[type=radio] {
cursor: pointer;
}
body {
background: url(http://s25.postimg.org/b6q25p4p7/black_thread.png) repeat black;
}
label {
color: #51634b;
}
#message {
color: #51634b;
font-size: 15px;
}
.btn {
display: block;
width: 120px;
height: 30px;
background-color: transparent;
color: black;
border: 2px solid #51634b;
border-radius: 5px;
cursor: pointer;
color: #51634b;
font-size: 15px;
margin: 15px;
margin: 0 auto;
}
.btn::-moz-focus-inner {
border: 0;
}
.btn:hover {
-webkit-animation: btn 0.5s 1;
-moz-animation: btn 0.5s 1;
-o-animation: btn 0.5s 1;
animation: btn 0.5s 1;
background-color: #51634b;
color: #000000;
}
input.btn:active {
padding: 0;
}
#-webkit-keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}
#-moz-keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}
#-o-keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}
#keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}

Categories