Sample Calculator Application - javascript

I just made a simple calculator application with AngularJS.
What does this program can do:
Catch error input when I press . 2 times per series of numbers.
Only accept 10 numbers per series of numbers.
Check if not complete operate.
User only can do 1 formula per 1 series of numbers.
But there are still some bugs:
When max 10 numbers, if you press delete, the program still accepts more than 10 numbers?
Some time after calculation, the program allows to input max 12 numbers?
var mainApp = angular.module("mainApp", []);
mainApp.controller('CalCtrl', function($scope) {
$scope.output = "0";
$scope.curIndex = 0;
$scope.result = 0;
$scope.checkInput = function(num) {
var tmp = true;
if($scope.result != 0) {
$scope.result = 0;
$scope.output = "0";
tmp = true;
}
if(angular.equals('+', num) ||
angular.equals('-', num) ||
angular.equals('*', num) ||
angular.equals('/', num)) {
var index = "+|-|*|/".indexOf($scope.output.charAt($scope.output.length - 1));
if(index >= 0) {
tmp = false;
$scope.msg = "You only can do 1 formula per 1 time.";
}
$scope.curIndex = $scope.output.length + 1;
} else {
tmp = true;
if($scope.output.substring($scope.curIndex).length < 10) {
if(angular.equals(num, ".")) {
var k = 0;
for(var j = 0; j < $scope.output.substring($scope.curIndex).length; j++){
if(angular.equals(".", $scope.output.substring($scope.curIndex).charAt(j))) {
k = k + 1;
}
}
if(k >= 1){
$scope.msg = "You can't add '.' 2 times per series of numbers!";
tmp = false;
}
} else {
tmp = true;
}
} else {
$scope.msg = "You can't input more than 10 number per series of numbers!";
tmp = false;
}
}
return tmp;
}
$scope.operate = function(op) {
if($scope.checkInput(op)) {
$scope.output = $scope.output + op;
}
}
$scope.press = function(num) {
if($scope.checkInput(num)) {
if(angular.equals(num, 'x')){
$scope.output = $scope.output.slice(0 , $scope.output.length - 1);
} else {
if (angular.equals($scope.output, "0")) {
$scope.output = "";
$scope.msg = "";
$scope.output += num;
} else if (angular.equals(".", $scope.output)){
$scope.msg = "";
$scope.output = "0.";
$scope.output += num;
} else {
$scope.msg = "";
$scope.output += num;
}
}
} else {
if(angular.equals(num, 'x')){
$scope.msg = "";
$scope.output = $scope.output.slice(0 , $scope.output.length - 1);
}
}
}
$scope.equal = function() {
var isOpEnd = "+|-|*|/".indexOf($scope.output.charAt($scope.output.length - 1));
if(isOpEnd >= 0) {
$scope.msg = "You must complete the formula first!";
} else if(eval($scope.output) == 0){
$scope.output = "0";
} else {
$scope.msg = "";
$scope.result = eval($scope.output);
$scope.output = $scope.result;
}
}
});
table, th, td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="mainApp" align="center">
<h2>AngularJS Calculator Application by Rain</h2>
<div ng-controller="CalCtrl">
<table width="250px" height="300px" align="center">
<tr>
<td colspan="4">
<input type="text" style="text-align:center; width: 236px; height:30px" name="output" id="res" value="{{output}}" disabled = "disabled">
</td>
</tr>
<tr>
<td colspan="4">
<button title="Number 1" style="width:56px" ng-click="press('1')">1</button>
<button title="Number 2" style="width:56px" ng-click="press('2')">2</button>
<button title="Number 3" style="width:56px" ng-click="press('3')">3</button>
<button title="Operate +" style="width:56px" ng-click='operate("+")' >+</button>
</td>
</tr>
<tr>
<td colspan="4">
<button style="width:56px" ng-click="press('4')">4</button>
<button style="width:56px" ng-click="press('5')">5</button>
<button style="width:56px" ng-click="press('6')">6</button>
<button title="Operate -" style="width:56px" ng-click='operate("-")' >-</button>
</td>
</tr>
<tr>
<td colspan="4">
<button title="Number 7" style="width:56px" ng-click="press('7')">7</button>
<button title="Number 8" style="width:56px" ng-click="press('8')">8</button>
<button title="Number 9" style="width:56px" ng-click="press('9')">9</button>
<button title="Operate *" style="width:56px" ng-click='operate("*")' >x</button>
</td>
</tr>
<tr>
<td>
<button title="Number 0" style="width:56px" ng-click="press('0')">0</button>
<button title="." style="width:56px" ng-click="press('.')">.</button>
<button title="Clear all" style="width:56px" ng-click="output = '0'">C</button>
<button title="Operate ÷" style="width:56px" ng-click='operate("/")' >÷</button>
</td>
</tr>
<tr>
<td>
<button style="width:175px" ng-click="equal()">=</button>
<button title="Delete" style="width:56px" ng-click="press('x')">⌫</button>
</td>
</tr>
</table>
<span align="center" style="color:red">{{msg}}</span>
</div>
</div>

Related

Getting an Uncaught TypeError that is preventing a score alert that I'm unsure how to fix even though my game plays as normal

So with my Yahtzee code, my game plays normally, but I am unable to get my alert for the total score and the alert that you received bonus points. I've discovered where the issues are I'm just unsure as to how to fix it. I tried debugging through alerts and from what I can gather it seems like the dice rolls aren't adding together to make the total unless my assumption is wrong.
Error I am Receiving
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Yahtzee</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style>
........
</style>
<script>
.......
</script>
</head>
<body style="background-color: black;" onload="getUser()">
<div class="container">
<header id="pageHeader">
<h1> <img src="yahtzee.jpg" width="100px"> YAHTZEE </h1>
</header>
<ul class="nav nav-pills red">
<li class="active"> Color Scheme </li>
</ul>
<br>
<div class="container">
<div class="row">
<div class="col-sm">
<table>
<br>
<span style="color: white"> Player Name: </span>
<span style="color: white" id="player"> </span>
<br>
<span style="color:white;"> <strong> SCORE BOARD </strong> </span>
<br>
<tr>
<th> Win Points </th>
<th> 200</th>
</tr>
<tr>
<td> Wins </td>
<td> 0 </td>
</tr>
<tr>
<td> Losses </td>
<td> 0 </td>
</tr>
</table>
</div>
<div class="col-4">
<table class="table table-bordered border-dark border border-2 table-md">
<tr>
<th>Upper Section</th>
<th>How to Score</th>
<th>Game #1</th>
</tr>
<tr>
<td> ACE <img src="Die1.PNG" width="45px"> = 1 </td>
<td> COUNT AND ADD ONLY ACES </td>
<td><div id="aces1"></div></td>
</tr>
<tr>
<td> TWOS <img src="Die2.PNG" width="45px"> = 2 </td>
<td> COUNT AND ADD ONLY TWOS </td>
<td><div id="twos1"></div></td>
</tr>
<tr>
<td> THREES <img src="Die3.PNG" width="45px"> = 3</td>
<td> COUNT AND ADD ONLY THREES</td>
<td><div id="threes1"></div></td>
</tr>
<tr>
<td> FOURS <img src="Die4.PNG" width="45px"> = 4 </td>
<td> COUNT AND ADD ONLY FOURS </td>
<td><div id="fours1"></div></td>
</tr>
<tr>
<td> FIVES <img src="Die5.PNG" width="45px"> = 5</td>
<td>COUNT AND ADD ONLY FIVES</td>
<td><div id="fives1"></div></td>
</tr>
<tr>
<td> SIXES <img src="Die6.PNG" width="45px"> = 6 </td>
<td> COUNT AND ADD ONLY SIXES </td>
<td><div id="sixes1"></div></td>
</tr>
<tr>
<td> 3 OF A KIND </td>
<td> ADD TOTAL OF ALL DICE </td>
<td></td>
</tr>
<tr>
<td> 4 OF A KIND </td>
<td> ADD TOTAL OF ALL DICE </td>
<td></td>
</tr>
<tr>
<td> FULL HOUSE </td>
<td> SCORE 25 </td>
<td></td>
</tr>
<tr>
<td style="font-size: 30px"> TOTAL SCORE </td>
<td> <img src="whitearrow.png" width="100px" > </td>
<td></td>
</tr>
<tr>
<td style="font-size: 30px"> BONUS w/ total score </td>
<td style="font-size: 30px"> SCORE 35 </td>
<td></td>
</tr>
<tr>
<td style="font-size: 30px"> TOTAL </td>
<td> <img src="whitearrow.png" width="100px" > </td>
<td></td>
</tr>
</table>
</div>
<div id="yourRoll" class="col-sm">
<h2 style="color: white"> Your Roll </h2>
<div id="die1">
<img src="Die1.PNG" width="45px">
</div>
Die 1 <input type="checkbox" name="options" id="cdie1" />
<div id="die2">
<img src="Die2.PNG" width="45px">
</div>
Die 2 <input type="checkbox" name="options" id="cdie2" />
<div id="die3">
<img src="Die3.PNG" width="45px">
</div>
Die 3 <input type="checkbox" name="options" id="cdie3" />
<div id="die4">
<img src="Die4.PNG" width="45px">
</div>
Die 4 <input type="checkbox" name="options" id="cdie4" />
<div id="die5">
<img src="Die5.PNG" width="45px">
</div>
Die 5 <input type="checkbox" name="options" id="cdie5" />
<div id="die6">
<img src="Die6.PNG" width="45px">
</div>
Die 6 <input type="checkbox" name="options" id="cdie6" />
<br>
<div>
</br>
<p> Rolls Left: <span id="rollsRem"> 2 </span> Turns Left: <span id='turnsLeft'> 5 </span> </p>
</br>
<button type="button" id="rollbutt" onclick="roll();" style="color: black"> Roll Button </button>
</br>
<button style="color: black" type="button" id="reset"> Reset </button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
body {
display: grid;
grid-template-areas:
"header";
}
#pageHeader {
grid-area: header;
}
header {
background: black;
}
header h1 {
font-family: Verdana;
font-size: 32px;
color: white;
}
.nav-pills > li.active > a, .nav-pills > li.active > a:focus {
color: black;
background-color: #f80000;
}
.nav-pills > li.active > a:hover {
background-color: #f80000;
color:black;
}
th, td {
border-style:solid;
border-color: white;
font-family: "Arial Rounded MT Bold";
font-weight: bolder;
border-width: 2px;
color: white;
}
#scoreCard {
right: 500px;
top: 150px;
border-style:solid;
border-color: black;
font-family: "Arial Rounded MT Bold";
font-weight: bolder;
width: 300px;
}
#yourRoll {
color: white;
}
div h2 img {
color: white;
float: right;
padding-right: 150px;
}
let dice = [
{'img':"Die1.PNG", 'value': 1},
{'img':"Die2.PNG", 'value': 2},
{'img':"Die3.PNG", 'value': 3},
{'img':"Die4.PNG", 'value': 4},
{'img':"Die5.PNG", 'value': 5},
{'img':"Die6.PNG", 'value': 6}
]
let checkedDice = [
{'dice':0, 'checked': false, 'id' : "die1"},
{'dice':0, 'checked': false, 'id' : "die2"},
{'dice':0, 'checked': false, 'id' : "die3"},
{'dice':0, 'checked': false, 'id' : "die4"},
{'dice':0, 'checked': false, 'id' : "die5"},
{'dice':0, 'checked': false, 'id' : "die6"},
]
let scoreCard = [
{'num' : 1, 'value' : 0, 'area' : "aces1"},
{'num' : 2, 'value' : 0, 'area' : "twos1"},
{'num' : 3, 'value' : 0, 'area' : "threes1"},
{'num' : 4, 'value' : 0, 'area' : "fours1"},
{'num' : 5, 'value' : 0, 'area' : "fives1"},
{'num' : 6, 'value' : 0, 'area' : "sixes1"},
]
var turns = 5;
var savedValue = 0;
var keeper = 0;
var rollsRem = 3;
var wins =0;
var losses = 0;
const winPoints = 200;
function getUser()
{
document.getElementById("player").innerHTML = prompt(" Please Enter your name: ");
}
// Function that will roll dice
function roll() {
if (rollsRem > 0) {
for (let i = 0; i < checkedDice.length; i++) {
if (checkedDice[i].checked == false) {
let rollDice = Math.floor(Math.random() * 6);
document.getElementById(checkedDice[i].id).innerHTML = `<img src="${dice[rollDice].img}" width='45px'>`;
checkedDice[i].value = dice[rollDice].value;
}
}
rollsRem--;
var display = document.getElementById("rollsRem");
display.innerHTML = rollsRem;
} else {
nextRound();
for(let j = 0; j < checkedDice.length; j++)
{
checkedDice[j].checked = false;
//rollsRem = 4;
}
}
}
$( document ).ready(function() {
reset();
function reset() {
roll();
}
$("#reset").click(function () {
alert("reset this");
rollsRem = 3;
var display = document.getElementById("rollsRem");
display.innerHTML = rollsRem;
roll();
$('input[type=checkbox]:checked').each(function () {
$(this).prop('checked', false);
});
$('input[type=checkbox]:checked').each(function () {
$(this).prop('value', 0);
});
turns--;
document.getElementById("turnsLeft").innerHTML = `${turns}`;
})
$("#cdie1").click(function () {
if (checkedDice[0].checked) {
checkedDice[0].checked = false;
} else {
checkedDice[0].checked = true;
}
})
$("#cdie2").click(function () {
if (checkedDice[1].checked) {
checkedDice[1].checked = false;
} else {
checkedDice[1].checked = true;
}
})
$("#cdie3").click(function () {
if (checkedDice[2].checked) {
checkedDice[2].checked = false;
} else {
checkedDice[2].checked = true;
}
})
$("#cdie4").click(function () {
if (checkedDice[3].checked) {
checkedDice[3].checked = false;
} else {
checkedDice[3].checked = true;
}
})
$("#cdie5").click(function () {
if (checkedDice[4].checked) {
checkedDice[4].checked = false;
} else {
checkedDice[4].checked = true;
}
})
$("#cdie6").click(function () {
if (checkedDice[5].checked) {
checkedDice[5].checked = false;
} else {
checkedDice[5].checked = true;
}
})
});
// Adds points into the scorecard, provides total score, as well as enters the next turn
// function nextRound() {
// let keeper;
// let sumRound = 0;
// let totalSum = 0;
// let bonus = 35;
//
// if (turns > 0) {
//
// keeper = prompt("Which Numbers Would You Want to keep?: ")
//
// for (let i = 0; i < checkedDice.length; i++) {
// if (checkedDice[i].value == keeper) {
// sumRound += checkedDice[i].value
// }
// }
// scoreCard[keeper - 1].value = sumRound;
//
// document.getElementById(scoreCard[keeper - 1].area).innerHTML = sumRound.toString();
// // alert("Did it make it here?")
//
// } else {
// // alert("In the else?")
// keeper = prompt("Choose which die to keep ");
//
// for(let i = 0; i < checkedDice.length; i++){
// if(checkedDice[i].value == keeper){
// sumRound += checkedDice[i].value;
// }
// }
// //alert("around here?")
// scoreCard[keeper-1].value = sumRound;
// document.getElementById(scoreCard[keeper-1].area).innerHTML = sumRound.toString();
//
// for(let j = 0; j < checkedDice.length+1; j++){
// //alert("maybe here?")
// totalSum += scoreCard[j].value;
// }
//
// document.getElementById("sum1").innerHTML = totalSum.toString();
// // alert("Here?")
// if(totalSum > 62){
// totalSum += bonus;
// alert("You get a bonus for more than 63 points!")
// document.getElementById("bonus1").innerHTML = bonus.toString();
// document.getElementById("sum1").innerHTML = totalSum.toString();
// }
// else {
// document.getElementById("bonus1").innerHTML = "0";
// }
//
// alert("Game Over. Score is " + totalSum)
//
// }
// }
function nextRound(){
let keep = 0;
let totalSum= 0;
let roundSum = 0;
let bonus = 35;
if (turns > 0) {
keep = prompt("What number do you wish to keep? ");
for (let i = 0; i < checkedDice.length; i++) {
if (checkedDice[i].value == keep) {
roundSum += checkedDice[i].value
}
}
scoreCard[keep - 1].value = roundSum;
document.getElementById(scoreCard[keep - 1].area).innerHTML = roundSum.toString();
}
else
{
keep = prompt("What number do you wish to keep? ");
for (let i = 0; i < checkedDice.length; i++) {
if (checkedDice[i].value == keep) {
roundSum += checkedDice[i].value
}
}
scoreCard[keep - 1].value = roundSum;
document.getElementById(scoreCard[keep - 1].area).innerHTML = roundSum.toString();
for (let j = 0; j < checkedDice.length + 1; j++)
{
totalSum += scoreCard[j].value;
}
document.getElementById("total1").innerHTML = totalSum.toString();
if (totalSum > 62)
{
totalSum += bonus;
alert("You get a bonus!!")
document.getElementById("bonus1").innerHTML = bonus.toString();
document.getElementById("total1").innerHTML = totalSum.toString();
}
else
{
document.getElementById("bonus1").innerHTML = "0";
}
alert("Game is over. You achieved a score of " + totalSum + "!");
alert("game over")
}
}
This is your definition/initialization for the checkedDice array
let checkedDice = [
{'dice':0, 'checked': false, 'id' : "die1"},
{'dice':0, 'checked': false, 'id' : "die2"},
{'dice':0, 'checked': false, 'id' : "die3"},
{'dice':0, 'checked': false, 'id' : "die4"},
{'dice':0, 'checked': false, 'id' : "die5"},
{'dice':0, 'checked': false, 'id' : "die6"},
]
Notice that none of the objects in the array has a "value" property
The only place I see that the value property can be created/set is in the roll function
if (checkedDice[i].checked == false) {
let rollDice = Math.floor(Math.random() * 6);
document.getElementById(checkedDice[i].id).innerHTML = `<img src="${dice[rollDice].img}" width='45px'>`;
checkedDice[i].value = dice[rollDice].value;
}
But, its theoretically possible to have object that never gets a value property added beacuse in that function, the line that sets the .value property is buried within an IF block. So, if whenever roll runs there is an object in checkedDice that has never had .checked == false, then that object never gets a .value property created and you end up getting the typeof error because that property is undefined when you try to reference it in later IF statements
Easy fix is to add the value property with an initial value to each object in the checkedDice array when it is initialized.

Javascript Interval continues endless without conditions met

var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>
Instruction___: doubleclick and hold
Im really really helpless in finding that bug tried to find where it originates, and build in couple of booleans so the loop only runs if theyre true but they were all false and it still continued running.
Im looking for a solution or a good way to adress the problem:(
What i found very noteworthy is that it only occurs when doing the needed keypresses fast, if done slower it doesnt result in that bug, also when done multiple times, it loops multiple times.
Just like Bergi said, your debounce function is broken. You need to initialize the timer variable outside the returned function.
This is your implementation:
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
And this is how you fix your bug:
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>

HTML, CSS, javascript calculator

Im having problems with my calculator. The buttons work and all align right but I can't get anything to show up on the monitor box or calculate anything. I listed my code below can anyone help me find where I went wrong? I feel it has to do with the true or false but I can't figure it out.
Here is the HTML code:
<body>
<table>
<tr>
<input id="display" type="text" value="0"/><span id="currOp"></span>
<tr>
<td>
<button id="7" class="num">7</button>
</td>
<td>
<button id="8" class="num">8</button>
</td>
<td>
<button id="9" class="num">9</button>
</td>
<td>
<button id="plus" class="operator">+</button>
</td>
<td>
<button id="clear">C</button>
</td>
</tr>
<tr>
<td>
<button id="4" class="num">4</button>
</td>
<td>
<button id="5" class="num">5</button>
</td>
<td>
<button id="6" class="num">6</button>
</td>
<td>
<button id="minus" class="operator">-</button>
</td>
<td>
<button id="root">√</button>
</td>
</tr>
<tr>
<td>
<button id="1" class="num">1</button>
</td>
<td>
<button id="2" class="num">2</button>
</td>
<td>
<button id="3" class="num">3</button>
</td>
<td>
<button id="mult" class="operator">x</button>
</td>
<td>
<button id="power" class="operator">x^y</button>
</td>
</tr>
<tr>
<td>
<button id="0" class="num">0</button>
</td>
<td>
<button id="decimal">.</button>
</td>
<td>
<button id="invert">±</button>
</td>
<td>
<button id="divid" class="operator">÷</button>
</td>
<td>
<button id="equals">=</button>
</td>
</tr>
Here is the CSS code:
button {
height: 40px;
width: 40px;
font-size: 110%;
}
#display{
font-size: 120%;
text-align: right;
}
span {
font-size: 150%;
}
and here is the javascript code:
var isOperating = true;
var isfloating = false;
var toBeCleared = true;
var operator;
var operand;
var display;
$(document).ready(init);
function init() {
display = $('#display');
$('.num').on('click', numClicked);
$('.operator').on('click', operatorClicked);
$('#invert').on('click', invertClicked);
$('#root').on('click', rootClicked);
$('#decimal').on('click', decimalClicked);
$('#equals').on('click', equalsClicked);
$('#clear').on('click', clearClicked);
}
function numClicked() {
var currVal = display.val();
var clickedNum = $(this).text();
if (currVal === "0" || toBeCleared) {
toBeCleared = true;
display.val(clickedNum);
} else {
display.val(currVal + clickedNum);
}
}
function invertClicked() {
display.val(display.val() * -1);
}
function rootClicked() {
display.val(Math.sqrt(evaluate()));
}
function decimalClicked() {
if (toBeCleared) {
display.val('0.');
toBeCleared = true;
} else {
if (!isFloating) {
display.val(display.val().concat('.'));
}
}
isFloating = false;
}
function equalsClicked() {
display.val(evaluate());
reset();
}
function clearClicked() {
reset();
display.val('0');
}
function reset() {
toBeCleared = true;
isOperating = true;
isFloating = false;
operator = null;
operand = null;
$('#currOp').text('');
}
function operatorClicked() {
if (isOperating) {
display.val(evaluate());
}
switch ($(this).attr('id')) {
case 'plus': operator = '+'; break;
case 'minus': operator = '-'; break;
case 'mult': operator = 'x'; break;
case 'divide': operator = '÷'; break;
case 'power': operator = '^'; break;
}
operand = parseFloat(display.val());
isOperating = true;
toBeCleared = true;
$('#currOp').text(operator);
}
function evaluate() {
`enter code here` var currVal = parseFloat(display.val());
var result;
switch (operator) {
case '+': result = operand + currVal; break;
case '-': result = operand - currVal; break;
case 'x': result = operand * currVal; break;
case '÷':
if (currVal === 0) {
result = 'Err';
} else {
result = operand / currVal;
}
break;
case '^': result = Math.pow(operand, currVal); break;
default: result = currVal;
}
return result;
}
You should set toBeCleared = false;
if (currVal === "0" || toBeCleared) {
toBeCleared = false;
display.val(clickedNum);
} else {
display.val(currVal + clickedNum);
}

Vanilla JavaScript calculator

So I've been working on a "very simple" calculator only using vanilla JavaScript. However I don't know why is it now working.
This is my JavaScript and HTML code:
(function() {
"use strict";
var elem = function(element) {
if (element.charAt(0) === "#") {
return document.querySelector(element);
}
return document.querySelectorAll(element);
};
// Variables
var screen = elem('.screen');
equal = elem('.equal');
nums = elem('.num');
ops = elem('.operator');
theNum = "";
oldNum = "";
resultNum;
operator;
// When: Number is clicked. Get the current number selected
var setNum = function() {
if (resultNum) {
theNum = this.getAttribute('data-num');
resultNum = "";
} else {
theNum += this.getAttribute('data-num');
}
viewer.innerHTML = theNum;
};
var moveNum = function() {
oldNum = theNum;
theNum = "";
operator = this.getAttribute('data-ops');
equal.setAttribute('data-result', '');
};
var displayNum = function() {
oldNum = parseFloat(oldNum);
theNum = parseFloat(theNum);
switch (operator) {
case "plus":
resultNum = oldNum + theNum;
break;
case "minus":
resultNum = oldNum - theNum;
break;
case "times":
resultNum = oldNum * theNum;
break;
case "divided by":
resultNum = oldNum / theNum;
break;
default:
resultNum = theNum;
}
viewer.innerHTML = resultNum;
equal.setAttribute("data-result", resultNum);
oldNum = 0;
theNum = resultNum;
};
var clearAll = function() {
oldNum = "";
theNum = "";
viewer.innerHTML = "0";
equals.setAttribute("data-result", resultNum);
};
for (var i = 0, l = nums.length; i < l; i++) {
nums[i].onclick = setNum;
}
for (var i = 0, l = ops.length; i < l; i++) {
ops[i].onclick = moveNum;
}
equals.onclick = displayNum;
elem("#clear").onclick = clearAll;
<div id="calculator">
<div class="top">
<button id="clear">C</button>
<div class="screen"></div>
</div>
<div class="btns">
<button class="num" data-num="7">7</button>
<button class="num" data-num="8">8</button>
<button class="num" data-num="9">9</button>
<button class="operator" data-ops="plus">+</button>
<button class="num" data-num="4">4</button>
<button class="num" data-num="5">5</button>
<button class="num" data-num="6">6</button>
<button class="operator" data-ops="minus">-</button>
<button class="num" data-num="1">1</button>
<button class="num" data-num="2">2</button>
<button class="num" data-num="3">3</button>
<button class="operator" data-ops="divided by">÷</button>
<button class="num" data-num="0">0</button>
<button class="num" data-num=".">.</button>
<button class="equal" data-result="">=</button>
<button class="operator" data-ops="times">x</button>
</div>
</div>
I'm not sure if what I'm doing is correct. I've been pretty much improvising but if anyone knows an easier way or correct way of making the calculator work I'd really appreciate the help.
I wrote a basic calculator for a school assignment back in 2003. Even though the code is 12+ years old, it still works in modern browsers today. Feel free to check it out any borrow any code you might find useful.
You can find the complete code below as well as in this github repository.
By the way, the behavior of my calculator is intended to work exactly like that of a real, physical, old school calculator... which means that you need to push the on/c button before you can do anything else ;-)
A screenshot :
The code :
var on = false, lastprinted = "", currentfunc ="", memory;
function testoverflow() {
var overflowflag;
if (memory >= 1000000000000) {
turn("error");
overflowflag = true;
} else
overflowflag = false;
return overflowflag;
}
function findmaxlength(location) {
var maxlength = 12;
if (location.indexOf("-", 0) != -1) maxlength++;
if (location.indexOf(".", 0) != -1) maxlength++;
return maxlength;
}
function showresult(lg, hf) {
memory = memory.toString();
memory = parseFloat(memory.substring(0,findmaxlength(memory)));
document.calculator.display.value = memory;
lastprinted = lg;
currentfunc = hf;
}
function turn(onoff) {
if (onoff == "ce") {
if (on) {
document.calculator.display.value="0";
}
} else {
switch (onoff) {
case "onc":
document.calculator.display.value="0";
on = true;
break;
case "error":
document.calculator.display.value = "ERROR";
break;
case "off":
document.calculator.display.value="";
on = false;
break;
}
currentfunc = "";
memory = null;
}
lastprinted = "";
}
function number(input) {
if (on) {
if ((document.calculator.display.value.length < findmaxlength(document.calculator.display.value)) || (lastprinted != "number")) {
if (!((document.calculator.display.value == "0") && ((input == "00") || (input == "0")))) {
if ((lastprinted == "number")&&(document.calculator.display.value != "0")) {
document.calculator.display.value += input;
lastprinted = "number";
} else if (input != "00") {
document.calculator.display.value = input;
lastprinted = "number";
}
}
}
}
}
function func(symbool) {
if ((on) && (document.calculator.display.value != "ERROR")) {
if (memory == null) {
memory = parseFloat(document.calculator.display.value);
lastprinted = "func";
currentfunc = symbool;
} else if ((document.calculator.display.value == "0") && (currentfunc == "/")) {
turn("error");
} else {
eval("memory = " + memory + currentfunc + "(" + document.calculator.display.value +");");
if (! testoverflow()) showresult("func", symbool);
}
}
}
function result(name) {
var value;
if ((on) && (document.calculator.display.value != "ERROR")) {
if (memory != null) {
value = document.calculator.display.value;
if (name == "procent") value = memory * parseFloat(document.calculator.display.value)/ 100;
eval("memory = " + memory + currentfunc + "(" + value +");");
if (! testoverflow()) {
showresult("name", "");
memory = null;
}
}
}
}
function dot() {
var maxlength = 12;
if ((on) && (document.calculator.display.value != "ERROR")) {
if (document.calculator.display.value.indexOf("-", 0) != -1) maxlength++;
if (((lastprinted == "number") || (document.calculator.display.value="0")) && !(document.calculator.display.value.length >= maxlength) && (document.calculator.display.value.indexOf(".", 0) == -1)) {
document.calculator.display.value += ".";
lastprinted = "number";
}
}
}
function negative() {
if ((on) && (lastprinted == "number") && (document.calculator.display.value != "ERROR")) {
if (document.calculator.display.value.indexOf("-", 0) == -1) document.calculator.display.value = "-" + document.calculator.display.value;
else document.calculator.display.value = document.calculator.display.value.substring(1,14);
}
}
body {background-color: #CCCCCC; color: #555555; font-family: Arial; font-weight: bold; font-size: 8pt;}
a {color: #CC5555; text-decoration: none}
a:visited {color: #CC5555; text-decoration: none}
a:active {color: #FF0000; text-decoration: none}
a:hover {color: #FF0000; text-decoration: none}
.button {height: 30px; width: 40px; background-color: #555555; border-color: #555555; color:#FFFFFF;}
.invisbutton {height: 28px; width: 40px; background-color: #7555C6; border-color: #7555C6; border-style:solid;}
.display {height: 50px; width: 217px; background-color: #D6D39F; border-color: #000000; color:#222222; border-style: solid; text-align: right; font-size: 22pt;}
.redbutton {height: 30px; width: 40px; background-color: #EE0000; border-color: #EE0000; color:#FFFFFF;}
.yellowbutton {height: 30px; width: 40px; background-color: #EEEE00; border-color: #EEEE00; color:#000000;}
.device {height: 30px; width: 40px; background-color: #7555C6; border-color: #7555C6; border-style:ridge;}
<table class="device" cellspacing="20" cellpadding="0">
<tr>
<td align="center">
<form name="calculator">
<table>
<tr>
<td colspan="5"><input type="text" name="display" class="display" readonly='readonly'></td>
</tr>
<tr>
<td colspan="5"><input type="text" class="invisbutton" style="height:15px;" readonly='readonly'></td>
</tr>
<tr>
<td><input type="text" name="hidden" class="invisbutton" readonly='readonly'></td>
<td><input type="text" name="hidden2" class="invisbutton" readonly='readonly'></td>
<td><input type="button" name="off" class="redbutton" value="off" onclick="turn(this.name);"></td>
<td><input type="button" name="ce" class="yellowbutton" value="ce" onclick="turn(this.name);"></td>
<td><input type="button" name="onc" class="yellowbutton" value="on/c" onclick="turn(this.name);"></td>
</tr>
<tr>
<td><input type="button" name="number7" class="button" value="7" onclick="number(this.value);"></td>
<td><input type="button" name="number8" class="button" value="8" onclick="number(this.value);"></td>
<td><input type="button" name="number9" class="button" value="9" onclick="number(this.value);"></td>
<td><input type="button" name="procent" class="button" value="%" onclick="result(this.name);"></td>
<td><input type="button" name="plusmin" class="button" value="+/-" onclick="negative();"></td>
</tr>
<tr>
<td><input type="button" name="number4" class="button" value="4" onclick="number(this.value);"></td>
<td><input type="button" name="number5" class="button" value="5" onclick="number(this.value);"></td>
<td><input type="button" name="number6" class="button" value="6" onclick="number(this.value);"></td>
<td><input type="button" name="func-" class="button" value="-" onclick="func(this.name.substring(4, 5));"></td>
<td><input type="button" name="func/" class="button" value="/" onclick="func(this.name.substring(4, 5));"></td>
</tr>
<tr>
<td><input type="button" name="number1" class="button" value="1" onclick="number(this.value);"></td>
<td><input type="button" name="number2" class="button" value="2" onclick="number(this.value);"></td>
<td><input type="button" name="number3" class="button" value="3" onclick="number(this.value);"></td>
<td rowspan="2"><input type="button" name="func+" class="button" value="+" style="height: 64px" onclick="func(this.name.substring(4, 5));"></td>
<td><input type="button" name="func*" class="button" value="x" onclick="func(this.name.substring(4, 5));"></td>
</tr>
<tr>
<td><input type="button" name="number0" class="button" value="0" onclick="number(this.value);"></td>
<td><input type="button" name="number00" class="button" value="00" onclick="number(this.value);"></td>
<td><input type="button" name="dot" class="button" value="." onclick="dot();"></td>
<td><input type="button" name="equals" class="button" value="=" onclick="result(this.name);"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
Are you closing your IIFE at the end of your code? If not, add
})();
to the end of your file.
separate
// Variables
var screen = elem('.screen');
equal = elem('.equal');
nums = elem('.num');
ops = elem('.operator');
theNum = "";
oldNum = "";
resultNum;
operator;
by commas, not semicolons.
Also, viewer is not defined.
There might be other things, but that should be a start
remove the function itself
add var before declaring variables: equal to viewer
use: var equal = elem('.equal')[0]; because you will get an array of DOM objects by className, you need the first one
use: var viewer = elem('.screen')[0]; because you will get an array of DOM objects by className, you need the first one
declare var viewer = elem('.screen');
Two words in the code 'equals' should be 'equal', remove the 's' in the end of the word
And the working code is:
"use strict";
var elem = function(element) {
if (element.charAt(0) === "#") {
return document.querySelector(element);
}
return document.querySelectorAll(element);
};
// Variables
var screen = elem('.screen');
var equal = elem('.equal')[0];
var nums = elem('.num');
var ops = elem('.operator');
var theNum = "";
var oldNum = "";
var resultNum;
var operator;
var viewer = elem('.screen')[0];
// When: Number is clicked. Get the current number selected
var setNum = function() {
if (resultNum) {
theNum = this.getAttribute('data-num');
resultNum = "";
} else {
theNum += this.getAttribute('data-num');
}
viewer.innerHTML = theNum;
};
var moveNum = function() {
oldNum = theNum;
theNum = "";
operator = this.getAttribute('data-ops');
equal.setAttribute('data-result', '');
};
var displayNum = function() {
oldNum = parseFloat(oldNum);
theNum = parseFloat(theNum);
switch (operator) {
case "plus":{
resultNum = oldNum + theNum;
break;
}
case "minus":
resultNum = oldNum - theNum;
break;
case "times":
resultNum = oldNum * theNum;
break;
case "divided by":
resultNum = oldNum / theNum;
break;
default:
resultNum = theNum;
}
viewer.innerHTML = resultNum;
equal.setAttribute("data-result", resultNum);
oldNum = 0;
theNum = resultNum;
};
var clearAll = function() {
oldNum = "";
theNum = "";
viewer.innerHTML = "0";
equal.setAttribute("data-result", resultNum);
};
for (var i = 0, l = nums.length; i < l; i++) {
nums[i].onclick = setNum;
}
for (var i = 0, l = ops.length; i < l; i++) {
ops[i].onclick = moveNum;
}
equal.onclick = displayNum;
elem("#clear").onclick = clearAll;

Darts game - checking problems in AngularJS

There is the content of my AngularJS (JavaScript ) file:
// define new Angular module
var myApp = angular.module('myApp',[]);
myApp.controller('MyAppController',function($scope){
$scope.player = '';
$scope.players = [];
$scope.totalPoints = [];
$scope.flag = 1;
$scope.myNumberRegex = /[0-9]/;
$scope.last = {};
$scope.score = {};
$scope.winner = 0;
$scope.nextPlayer = '';
$scope.nextRound = false;
var actualPlayer = 0;
var pointsValue,round = 0;
var internalRoundCounter = 1;
var shootsString = '';
$scope.$watch('roundCount',function(value){
console.log('new value',value);
});
$scope.add = function(){
$scope.players.push({name: $scope.player, totalPoints: 0, fields:[]});
$scope.player = '';
};
$scope.checkForm = function() {
var valid = true;
if ($scope.players.length == 0) {
alert('There is no player added!');
valid = false;
}
if ($scope.roundCount < 3 || $scope.roundCount > 10) {
alert('Incorrect round count!');
valid = false;
}
if ($scope.players.length == 1) {
console.log('Tömb hossza: ', $scope.players.length);
alert('One player is not enough!');
valid = false;
}
if (valid) {
$scope.flag = 2;
var startingPlayer = $scope.players[actualPlayer].name;
$scope.nextPlayer = startingPlayer;
}
};
function showResults(){
$scope.flag = 3;
}
// watching changed value
$scope.$watch('last.id',function(newValue){
console.log('last.id changed',newValue);
pointsValue = 0;
//-----------------------------------------------------------
// checking target to calculate earned points
//-----------------------------------------------------------
if (newValue == "Bull") {
pointsValue += 50;
console.log(pointsValue);
}
else if (newValue == "Outer") {
pointsValue += 25;
console.log(pointsValue);
}
else if (['s','d','t'].indexOf(newValue[0]) != -1) {
var multiplier = 1;
if (newValue[0] == 'd')
multiplier = 2;
else if (newValue[0] == 't')
multiplier = 3;
var tmp = newValue.split("").splice(1,2).join("");
pointsValue += (tmp * multiplier);
}
//-----------------------------------------------------------
// while playing darts
if (round < $scope.roundCount) {
if (internalRoundCounter < 4){
shootsString += newValue+' ';
$scope.players[actualPlayer].totalPoints += pointsValue;
internalRoundCounter++;
}
else{
$scope.players[actualPlayer].fields.push({fieldId : round+1, fieldName : shootsString});
shootsString = '';
internalRoundCounter = 1;
actualPlayer++;
if (actualPlayer == $scope.players.length) {
actualPlayer = 0;
round++;
}
$scope.nextPlayer = $scope.players[actualPlayer].name;
}
}
// when game finished
else{
showResults();
$scope.winner = $scope.players[0].name;
// find winner in array
for (var i=1; i<$scope.players.length; i++){
if ($scope.players[i].totalPoints > $scope.players[i-1].totalPoints){
$scope.winner = $scope.players[i].name;
}
}
console.log($scope.players);
}
});
});
myApp.directive('dartClickListener', function() {
return {
restrict: 'A',
scope: false,
link: function(scope,element,attrs) {
console.log(angular.element(element));
angular.element(element).find('g').children().bind('click',function(){
console.log(angular.element(this).attr('id'));
scope.last.id = angular.element(this).attr('id');
scope.$apply();
});
}
}
});
<!DOCTYPE html>
<html ng-app="myApp" ng-init="roundCount=3">
<head lang="en">
<meta charset="UTF-8">
<title>.:: Darts ::.</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="myscript.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="MyAppController">
<div id="start" ng-show="flag == 1">
<div>
<h1 class="stdCell gameTitle">Darts</h1>
</div>
<div>
<table>
<tr>
<td><label class="stdCell" for="playerName">Add player</label></td>
<td><input type="text" id="playerName" ng-model="player"></td>
<td><input type="button" value="Add" ng-click="add()" ng-disabled="!(!!player)"></td>
</tr>
<tr>
<td><label class="stdCell" for="rounds">Rounds (3-10) </label></td>
<td colspan="2"><input type="text" id="rounds" ng-model="roundCount" ng-pattern="myNumberRegex" ng-required="true"></td>
</tr>
</table>
</div>
<div>
<button ng-disabled="!(!!roundCount)" ng-click="checkForm()">Start game</button>
</div>
</div>
<div ng-show="flag == 2">
<div id="gameState">
<div>
<table>
<tr><td class="stdCell borderedCell tableHeader">Player</td><td class="stdCell borderedCell tableHeader">Points</td></tr>
<tr ng-repeat="player in players"><td class="stdCell borderedCell">{{player.name}}</td><td class="stdCell borderedCell">{{player.totalPoints}}</td></tr>
</table>
</div>
<div>
<h2 class="stdCell" ng-model="nextPlayer">{{nextPlayer}} is next</h2>
</div>
</div>
<div id="darts">
<svg id="dartboard" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="630px" height="630px" viewBox="0 0 787 774" enable-background="new 0 0 787 774" xml:space="preserve">
<g id="areas" dart-click-listener="last.id">
<!-- svg file content -->
<div>
<h3 ng-model="winner" ng-repeat="player in players | filter:winner" class="stdCell">The winner: {{winner}} # points: {{player.totalPoints}}</h3>
</div>
<div>
<table>
<tr>
<td class="stdCell borderedCell tableHeader" rowspan="2">Player</td>
<td class="stdCell borderedCell tableHeader" colspan="{{players[0].fields.length}}">Round</td>
<td class="stdCell borderedCell tableHeader totalPointCell" rowspan="2">Total points</td>
</tr>
<tr>
<td class="stdCell borderedCell resultCell" ng-repeat="field in players[0].fields">{{field.fieldId}}</td>
</tr>
<tr ng-repeat="player in players">
<td class="stdCell borderedCell">{{player.name}}</td>
<td class="stdCell borderedCell resultCell" ng-repeat="field in player.fields">{{field.fieldName}}</td>
<td class="stdCell borderedCell resultCell">{{player.totalPoints}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Everything is about a darts game in AngularJS, but I have two problems with it:
1.) After every 3 shoots the player is changed. The shooting is checking in $scope.$watch('last.id' ...) section. My problem is that before changing a player, I must click once more on darts table, because the code is running only after clicking on either field of the table. How can I eliminate it?
2.) The second problem is, that I have to count also shoots, which not hit the table. How can I do it?
The dartboard is an SVG file, inserted into HTML code, the source is from: link.
Thank you very much for answers! :)

Categories

Resources