Darts game - checking problems in AngularJS - javascript

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! :)

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.

Sample Calculator Application

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>

How to disable div(s) until previous div has been filled in

I'm currently making a drag and drop quiz, as a start I have four questions in which answers can be picked up and dropped into the corresponding question. I want to disable the drop box for questions 2,3,4 until question 1 is answered. Then re-active q2 leaving 3,4 disabled and so on.... I'm quite new to JavaScript and have tried multiple ways to do this, including looking at other situations similar to mine on here but have yet succeeded! I have put a screenshot of the quiz so far which will hopefully make it clearer.
Hopefully someone can help, thanks!
All my code is below:
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="draganddrop.js"></script>
</head>
<body>
<div id="container">
<h1>SAN Failure</h1>
<p>Your SAN's RAID controller has failed and corrupted a significant amount of data. You need to contact your DR provider failover to your recovery environment whilst you restore your internal servers from backup images.</p>
</div>
<div id="mainContainer">
<div id="dragScriptContainer">
<div id="questionDiv">
<p><strong>Task one: Damage Control</strong></p>
<div class="dragDropSmallBox textbox" id="q1">1. Find the relevant IP address for the affected hardware</div><div class="destinationBox"></div>
<div class="dragDropSmallBox textbox" id="q2">2. Notify your disaster recovery provider</div><div class="destinationBox"></div>
<div class="dragDropSmallBox textbox" id="q3">3. Inform the team of directors of the situation</div><div class="destinationBox"></div>
<div class="dragDropSmallBox textbox disabled="true"" id="q4">4. Update the emergency phone message</div><div class="destinationBox"></div>
</div>
<div class="feedback">
<div id="feedback"></div>
<div id="counter">0</div>
<div id="result"></div>
</div>
<div class="container">
<h1 style="text-align:center">Disaster Recovery Runbook</h1>
<!-- Page 1 -->
<h5 style="color: red; ">Page 1</h5>
<h2>Executive Summary</h2>
<p>[ACME Ltd. company information]<br>ACME Ltd. currently has 9 virtual servers and 4 physical servers all hosted at an onsite data centre.<br>The key IT staff required for recovery are [IT Manager], [Backup Manager] and [Disaster Recovery Provider]. The servers must be recovered within 8 hours of invocation.
</p>
<!-- Page 2 -->
<h5 style="color: red; ">Page 2</h5>
<h2>Contents</h2>
<p><strong>
Invoking Disaster Recovery<br>
Key Contacts<br>
Call Tree<br>
Emergency Phone Message<br>
Network Diagram<br>
Recovery Locations<br>
Software License and Registration Keys<br>
Event Log<br>
Recovery Templates
</strong></p>
<!-- Page 3 -->
<h5 style="color: red; ">Page 3</h5>
<h2>Invoking Disaster Recovery</h2>
<p>If a crisis or disaster has occurred, the business continuity manager must decide the course of action. If, for whatever reason, the business continuity manager is unable to perform these duties, refer to the cascading decision-making hierarchy below.<br>Only the most senior member is authorized to invoke the DR plan, subject to availability.<br>1. Business Continuity Manager<br>2. IT Director<br>3. IT Manager<br>4. IT Administrator<br>In the event none of the stated staff members are available...good luck.</p>
<div id="answerDiv">
<!-- Page 4 -->
<h5 style="color: red; ">Page 4</h5>
<h2>Key Contacts</h2>
<main class="flex-center">
<table>
<tr>
<td><p><strong>Contact</strong></p></td>
<td><p><strong>Telephone Number</strong></p></td>
<td><p><strong>Email Address</strong></p></td>
</tr>
<tr>
<td><p>Managing Director</p></td>
<td><div class="dragDropSmallBox" id="a3">0123456789</div></td>
<td><div class="dragDropSmallBox" id="a10">M.D#acme.com</div></td>
</tr>
<tr>
<td><p>Financial Director</p></td>
<td><div class="dragDropSmallBox" id="a10">1234567890</div></td>
<td><div class="dragDropSmallBox" id="a10">F.D#acme.com</div></td>
</tr>
<tr>
<td><p>Business Continuity Manager</p></td>
<td><div class="dragDropSmallBox" id="a10">2345678901</div></td>
<td><div class="dragDropSmallBox" id="a10">B.C.D#acme.com</div></td>
</tr>
<tr>
<td><p>Sales Manager</p></td>
<td><div class="dragDropSmallBox" id="a10">3456789012</div></td>
<td><div class="dragDropSmallBox" id="a10">S.M#acme.com</div></td>
</tr>
<tr>
<td><p>Production Manager</p></td>
<td><div class="dragDropSmallBox" id="a10">4567890123</div></td>
<td><div class="dragDropSmallBox" id="a10">P.M#acme.com</div></td>
</tr>
<tr>
<td><p>HR Director</p></td>
<td><div class="dragDropSmallBox" id="a10">5678901234</div></td>
<td><div class="dragDropSmallBox" id="a10">H.R.D#acme.com</div></td>
</tr>
<tr>
<td><p>Backup Manger</p></td>
<td><div class="dragDropSmallBox" id="a10">6789012345</div></td>
<td><div class="dragDropSmallBox" id="a10">B.M#acme.com</div></td>
</tr>
<tr>
<td><p>Power Supplier</p></td>
<td><div class="dragDropSmallBox" id="a10">7890123456</div></td>
<td><div class="dragDropSmallBox" id="a10">P.S#acme.com</div></td>
</tr>
<tr>
<td><p>Internet Supplier</p></td>
<td><div class="dragDropSmallBox" id="a10">8901234567</div></td>
<td><div class="dragDropSmallBox" id="a10">I.S#acme.com</div></td>
</tr>
<tr>
<td><p>Disaster Recovery Supplier</p></td>
<td><div class="dragDropSmallBox" id="a2">9012345678</div></td>
<td><div class="dragDropSmallBox" id="a10">D.R.S#acme.com</div></td>
</tr>
</table>
</main>
<!-- Page 5 -->
<h5 style="color: red; ">Page 5</h5>
<h2>Call Tree</h2>
<img class="callTree" src="img/call_tree.jpg">
<!-- Page 6 -->
<h5 style="color: red; ">Page 6</h5>
<h2>Emergency Phone Message</h2>
<p>We have distributed emergency call cards to staff, containing the number for an emergency phone line in a disaster. You should update this message to alert your staff members to the presence of a disastrous event, and every time there is a change in circumstances - either towards or away from resolution.<br> To update the message call the number below:</p>
<div class="dragDropSmallBox" id="a4">UPDATE EMERGENCY PHONE LINE</div><br><br>
<!-- Page 7 -->
<h5 style="color: red; ">Page 7</h5>
<h2>Network Diagram with Service Information</h2>
<main class="flex-center">
<table>
<tr>
<td><p><strong>Service</strong></p></td>
<td><p><strong>IP Address</strong></p></td>
</tr>
<tr>
<td><p>Email</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.1</div></td>
</tr>
<tr>
<td><p>Web Server</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.2</div></td>
</tr>
</tr>
<tr>
<td><p>MPLS</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.3</div></td>
</tr>
<tr>
<td><p>VoIP</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.4</div></td>
</tr>
<tr>
<td><p>SAN Server</p></td>
<td><div class="dragDropSmallBox" id="a1">192.0.0.5</div></td>
</tr>
<tr>
<td><p>CRM Server</p></td>
<td><div class="dragDropSmallBox" id="a10">192.0.0.6</div></td>
</tr>
</table>
</main>
</div>
<div id="dragContent"></div>
</div>
</div>
</div>
<div id="buttons">
<input type="button" onclick="dragDropResetForm();return false" value="Reset">
<input type="button" onclick="clearFields();" id="clear" value="Clear">
<input type="button" onclick="showResults();" id="result" value="Result">
</div>
</body>
</html>
JAVASCRIPT:
var shuffleQuestions = true;
var shuffleAnswers = false;
var lockedAfterDrag = true;
function quizIsFinished()
{
alert('Finished!');
}
var dragContentDiv = false;
var dragContent = false;
var dragSource = false;
var dragDropTimer = -1;
var destinationObjArray = new Array();
var destination = false;
var dragSourceParent = false;
var dragSourceNextSibling = false;
var answerDiv;
var questionDiv;
var sourceObjectArray = new Array();
var arrayOfEmptyBoxes = new Array();
var arrayOfAnswers = new Array();
function getTopPos(inputObj)
{
if(!inputObj || !inputObj.offsetTop)return 0;
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
return returnValue;
}
function getLeftPos(inputObj)
{
if(!inputObj || !inputObj.offsetLeft)return 0;
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
function cancelEvent()
{
return false;
}
function initDragDrop(e)
{
if(document.all)e = event;
if(lockedAfterDrag && this.parentNode.parentNode.id=='questionDiv')return;
dragContentDiv.style.left = e.clientX + Math.max(document.documentElement.scrollLeft,document.body.scrollLeft) + 'px';
dragContentDiv.style.top = e.clientY + Math.max(document.documentElement.scrollTop,document.body.scrollTop) + 'px';
dragSource = this;
dragSourceParent = this.parentNode;
dragSourceNextSibling = false;
if(this.nextSibling)dragSourceNextSibling = this.nextSibling;
if(!dragSourceNextSibling.tagName)dragSourceNextSibling = dragSourceNextSibling.nextSibling;
dragDropTimer=0;
timeoutBeforeDrag();
return false;
}
function timeoutBeforeDrag(){
if(dragDropTimer>=0 && dragDropTimer<10){
dragDropTimer = dragDropTimer +1;
setTimeout('timeoutBeforeDrag()',10);
return;
}
if(dragDropTimer>=10){
dragContentDiv.style.display='block';
dragContentDiv.innerHTML = '';
dragContentDiv.appendChild(dragSource);
}
}
function dragDropMove(e)
{
if(dragDropTimer<10){
return;
}
if(document.all)e = event;
var scrollTop = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
dragContentDiv.style.left = e.clientX + scrollLeft + 'px';
dragContentDiv.style.top = e.clientY + scrollTop + 'px';
var dragWidth = dragSource.offsetWidth;
var dragHeight = dragSource.offsetHeight;
var objFound = false;
var mouseX = e.clientX + scrollLeft;
var mouseY = e.clientY + scrollTop;
destination = false;
for(var no=0;no<destinationObjArray.length;no++){
var left = destinationObjArray[no]['left'];
var top = destinationObjArray[no]['top'];
var width = destinationObjArray[no]['width'];
var height = destinationObjArray[no]['height'];
destinationObjArray[no]['obj'].className = 'destinationBox';
var subs = destinationObjArray[no]['obj'].getElementsByTagName('DIV');
if(!objFound && subs.length==0){
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destinationObjArray[no]['obj'].className='dragContentOver';
destination = destinationObjArray[no]['obj'];
objFound = true;
}
}
}
sourceObjectArray['obj'].className='';
if(!objFound){
var left = sourceObjectArray['left'];
var top = sourceObjectArray['top'];
var width = sourceObjectArray['width'];
var height = sourceObjectArray['height'];
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destination = sourceObjectArray['obj'];
sourceObjectArray['obj'].className='dragContentOver';
}
}
return false;
}
function dragDropEnd()
{
if(dragDropTimer<10){
dragDropTimer = -1;
return;
}
dragContentDiv.style.display='none';
sourceObjectArray['obj'].style.backgroundColor = '#FFF';
if(destination){
destination.appendChild(dragSource);
destination.className='destinationBox';
if(!destination.id || destination.id!='answerDiv'){
var previousEl = dragSource.parentNode.previousSibling;
if(!previousEl.tagName)previousEl = previousEl.previousSibling;
var numericId = previousEl.id.replace(/[^0-9]/g,'');
var numericIdSource = dragSource.id.replace(/[^0-9]/g,'');
if(numericId==numericIdSource){
dragSource.className='correctAnswer';
checkAllAnswers();
}
else
dragSource.className='wrongAnswer';
}
if(destination.id && destination.id=='answerDiv'){
dragSource.className='dragDropSmallBox';
}
} else{
if(dragSourceNextSibling)
dragSourceNextSibling.parentNode.insertBefore(dragSource,dragSourceNextSibling);
else
dragSourceParent.appendChild(dragSource);
}
if(numericId==numericIdSource) {
document.getElementById('feedback').innerHTML = "";
document.getElementById('feedback').innerHTML += 'Correct Answer!';
}
else {
document.getElementById('feedback').innerHTML = "";
document.getElementById('feedback').innerHTML += 'Incorrect Answer! Have you tried this...';
incrementScore();
}
dragDropTimer = -1;
dragSourceNextSibling = false;
dragSourceParent = false;
destination = false;
}
function checkAllAnswers()
{
for(var no=0;no<arrayOfEmptyBoxes.length;no++){
var sub = arrayOfEmptyBoxes[no].getElementsByTagName('DIV');
if(sub.length==0)return;
if(sub[0].className!='correctAnswer'){
return;
}
}
quizIsFinished();
}
function resetPositions()
{
if(dragDropTimer>=10)return;
for(var no=0;no<destinationObjArray.length;no++){
if(destinationObjArray[no]['obj']){
destinationObjArray[no]['left'] = getLeftPos(destinationObjArray[no]['obj'])
destinationObjArray[no]['top'] = getTopPos(destinationObjArray[no]['obj'])
}
}
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
}
function initDragDropScript()
{
dragContentDiv = document.getElementById('dragContent');
answerDiv = document.getElementById('answerDiv');
answerDiv.onselectstart = cancelEvent;
var divs = answerDiv.getElementsByTagName('DIV');
var answers = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='dragDropSmallBox'){
divs[no].onmousedown = initDragDrop;
answers[answers.length] = divs[no];
arrayOfAnswers[arrayOfAnswers.length] = divs[no];
}
}
if(shuffleAnswers){
for(var no=0;no<(answers.length*10);no++){
var randomIndex = Math.floor(Math.random() * answers.length);
answerDiv.appendChild(answers[randomIndex]);
}
}
sourceObjectArray['obj'] = answerDiv;
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
sourceObjectArray['width'] = answerDiv.offsetWidth;
sourceObjectArray['height'] = answerDiv.offsetHeight;
questionDiv = document.getElementById('questionDiv');
questionDiv.onselectstart = cancelEvent;
var divs = questionDiv.getElementsByTagName('DIV');
var questions = new Array();
var questionsOpenBoxes = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='destinationBox'){
var index = destinationObjArray.length;
destinationObjArray[index] = new Array();
destinationObjArray[index]['obj'] = divs[no];
destinationObjArray[index]['left'] = getLeftPos(divs[no])
destinationObjArray[index]['top'] = getTopPos(divs[no])
destinationObjArray[index]['width'] = divs[no].offsetWidth;
destinationObjArray[index]['height'] = divs[no].offsetHeight;
questionsOpenBoxes[questionsOpenBoxes.length] = divs[no];
arrayOfEmptyBoxes[arrayOfEmptyBoxes.length] = divs[no];
}
if(divs[no].className=='dragDropSmallBox'){
questions[questions.length] = divs[no];
}
}
if(shuffleQuestions){
for(var no=0;no<(questions.length*10);no++){
var randomIndex = Math.floor(Math.random() * questions.length);
questionDiv.appendChild(questions[randomIndex]);
questionDiv.appendChild(questionsOpenBoxes[randomIndex]);
destinationObjArray[destinationObjArray.length] = destinationObjArray[randomIndex];
destinationObjArray.splice(randomIndex,1);
questionsOpenBoxes[questionsOpenBoxes.length] = questionsOpenBoxes[randomIndex];
questionsOpenBoxes.splice(randomIndex,1);
questions[questions.length] = questions[randomIndex];
questions.splice(randomIndex,1);
}
}
questionDiv.style.visibility = 'visible';
answerDiv.style.visibility = 'visible';
document.documentElement.onmouseup = dragDropEnd;
document.documentElement.onmousemove = dragDropMove;
setTimeout('resetPositions()',150);
window.onresize = resetPositions;
}
function incrementScore(){
counter = document.getElementById('counter');
counter.innerHTML++;
}
function showResults() {
result = document.getElementById('result');
if(counter.innerHTML < 2){
result.innerHTML += 'Well done!';
} else {
result.innerHTML += 'Not so great!';
}
}
/* Reset the form */
function dragDropResetForm()
{
for(var no = 0; no < arrayOfAnswers.length; no++){
arrayOfAnswers[no].className='dragDropSmallBox'
answerDiv.appendChild(arrayOfAnswers[no]);
}
document.getElementById('score').innerHTML = "";
}
function clearFields() {
document.getElementById("questionDiv").innerHTML = "";
}
window.onload = initDragDropScript;
I suggest you use jQueryUI draggable and droppable interactions to achieve what you want. They contain many methods and events which you can use, for example you can easily disable a droppable object by using $( ".selector" ).droppable( "disable" );. You can also save yourself the trouble of creating methods for dragging the elements.
I have create a very basic example that should help you out, however it can be improved :)
jsFiddle : https://jsfiddle.net/CanvasCode/hoeh0hds/1/
html
<input id="input1" />
<br />
<input id="input2" />
<br />
<input id="input3" />
<br />
<input id="input4" />
<br />
Javascript
document.getElementById('input2').disabled = true;
document.getElementById('input3').disabled = true;
document.getElementById('input4').disabled = true;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
inputs[index].addEventListener('input', function () {
// Input 1
if (this == document.getElementById('input1')) {
if (this.value.length) {
document.getElementById('input2').disabled = false;
} else {
document.getElementById('input2').disabled = true;
document.getElementById('input3').disabled = true;
document.getElementById('input4').disabled = true;
}
}
// Input 2
if (this == document.getElementById('input2')) {
if (this.value.length) {
document.getElementById('input3').disabled = false;
} else {
document.getElementById('input3').disabled = true;
document.getElementById('input4').disabled = true;
}
}
// Input 3
if (this == document.getElementById('input3')) {
if (this.value.length) {
document.getElementById('input4').disabled = false;
} else {
document.getElementById('input4').disabled = true;
}
}
});
}
Try removing the onmouseup and onmousedown eventlisteners till the div is ready for activity. The syntax below should work for that
document.getElementById("myDIV").removeEventListener("mouseup", dragDropEnd)
document.getElementById("myDIV").removeEventListener("mousedown", dragDropMove)

After setInterval( ) on click function will not work...Variable no longer increments

The code works for the most part.
Whenever the interval is set to refresh the game card, the onclick functions no longer work and the variable no longer increments.
What am I missing here?
You Can comment out the line with the setInterval() to see the desired outcome. It should refresh every second keeping the variable score and incrementing whenever someone clicks on the images. Thanks!
// var btn = document.getElementById('btn');
//btn.addEventListener('click', UpdateTable);
// Set the max length and Width
var maxWidth = 4;
var maxLength = 6;
// Returns a random number
function CreateRandom() {
return Math.floor(Math.random() * 2 + 1);
}
//function to create an image
function CreateGopher() {
var randomNumber = CreateRandom();
var image = "Sup";
if (randomNumber == 1) {
image = "<img src='gopher.jpg' class='gopher' height='100' width='100'>";
} else if (randomNumber == 2) {
image = "<img src='lettuce.jpg' class='lettuce' height='100' width='100'>";
}
return image;
}
//create table
function UpdateTable() {
// Iterate over each cell and set a random number
for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < maxWidth; j++) {
tmp = 'cell' + i + j;
document.getElementById(tmp).innerHTML = CreateGopher();
}
}
}
function newTable() {
// Iterate over each cell and set a random number
for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < maxWidth; j++) {
tmp = 'cell' + i + j;
document.getElementById(tmp).innerHTML = CreateGopher();
}
}
}
//Use The function update table
UpdateTable();
setTimeout(function() {
alert("Your Score is " + score)
}, 15000);
setInterval(UpdateTable, 1000);
var score = 0;
$(".lettuce").click(function() {
//alert( "You Clicked on the lettuce" );
score -= 5;
document.getElementById("scoreOut").innerHTML = score;
});
$(".gopher").click(function() {
//alert( "You Clicked on the lettuce" );
score += 5;
document.getElementById("scoreOut").innerHTML = score;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<center>
<div id="container">
<div id="header">
<h1>Welcome</h1>
<div id="scoreOut"></div>
</div>
<div id="content">
<table id="gameCard">
<tbody>
<tr>
<td id="cell00"> </td>
<td id="cell01"> </td>
<td id="cell02"> </td>
<td id="cell03"> </td>
</tr>
<tr>
<td id="cell10"> </td>
<td id="cell11"> </td>
<td id="cell12"> </td>
<td id="cell13"> </td>
</tr>
<tr>
<td id="cell20"> </td>
<td id="cell21"> </td>
<td id="cell22"> </td>
<td id="cell23"> </td>
</tr>
<tr>
<td id="cell30"> </td>
<td id="cell31"> </td>
<td id="cell32"> </td>
<td id="cell33"> </td>
</tr>
<tr>
<td id="cell40"> </td>
<td id="cell41"> </td>
<td id="cell42"> </td>
<td id="cell43"> </td>
</tr>
<tr>
<td id="cell50"> </td>
<td id="cell51"> </td>
<td id="cell52"> </td>
<td id="cell53"> </td>
</tr>
</tbody>
</table>
</div>
</div>
<br>
//<input id="btn" type="button" value="Play The Game!!" />
</center>
Figured it out!
Needed to put my JQUERY on.click goodies in the actual main function, which I did not have in the first place, in with the other functions nested in it.
<!--
To change this template use Tools | Templates.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Gopher Broke</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
#gameCard td{
padding:0; margin:0;
}
#gameCard {
border-collapse: collapse;
cursor:url(finger2.png), pointer;
}
</style>
</head>
<body>
<center>
<div id="container">
<div id="header">
<h1>GOPHER BROKE</h1>
<center>You have 15 seconds to stop as many gophers as possible!</center>
<div id="scoreOut">Score:</div>
<FORM>
<INPUT TYPE="button" onClick="history.go(0)" VALUE="Refresh">
</FORM>
</div>
<div id="content">
<table id="gameCard">
<tbody>
<tr>
<td id="cell00"> </td>
<td id="cell01"> </td>
<td id="cell02"> </td>
<td id="cell03"> </td>
</tr>
<tr>
<td id="cell10"> </td>
<td id="cell11"> </td>
<td id="cell12"> </td>
<td id="cell13"> </td>
</tr>
<tr>
<td id="cell20"> </td>
<td id="cell21"> </td>
<td id="cell22"> </td>
<td id="cell23"> </td>
</tr>
<tr>
<td id="cell30"> </td>
<td id="cell31"> </td>
<td id="cell32"> </td>
<td id="cell33"> </td>
</tr>
<tr>
<td id="cell40"> </td>
<td id="cell41"> </td>
<td id="cell42"> </td>
<td id="cell43"> </td>
</tr>
<tr>
<td id="cell50"> </td>
<td id="cell51"> </td>
<td id="cell52"> </td>
<td id="cell53"> </td>
</tr>
</tbody>
</table>
</div>
</div>
<br>
<!--<input id="btn" type="button" value="Play The Game!!" />-->
</center>
<script>
var score = 0;
function game(){
// var btn = document.getElementById('btn');
//btn.addEventListener('click', UpdateTable);
// Set the max length and Width
var maxWidth = 4;
var maxLength = 6;
// Returns a random number
function CreateRandom() {
return Math.floor(Math.random() * 4 + 1);
}
//function to create an image
function CreateGopher() {
var randomNumber = CreateRandom();
var image = "Sup";
if(randomNumber == 1){
image = "<img src='gopher.jpg' class='gopher' height='50' width='50'>";
}
else if(randomNumber == 2){
image = "<img src='lettuce.jpg' class='lettuce' height='50' width='50'>";
}
else if(randomNumber == 3){
image = "<img src='lettuce.jpg' class='lettuce' height='50' width='50'>";
}
else if(randomNumber == 4){
image = "<img src='lettuce.jpg' class='lettuce' height='50' width='50'>";
}
return image;
}
//create table
function UpdateTable() {
// Iterate over each cell and set a random number
for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < maxWidth; j++) {
tmp = 'cell' + i + j;
document.getElementById(tmp).innerHTML = CreateGopher();
}
}
}
function newTable() {
// Iterate over each cell and set a random number
for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < maxWidth; j++) {
tmp = 'cell' + i + j;
document.getElementById(tmp).innerHTML = CreateGopher();
}
}
}
//Use The function update table
UpdateTable();
$( ".lettuce" ).click(function() {
//alert( "You Clicked on the lettuce" );
score -= 5;
document.getElementById("scoreOut").innerHTML = "<h1>Score :" + score;
});
$( ".gopher" ).click(function() {
//alert( "You Clicked on the lettuce" );
score += 5;
document.getElementById("scoreOut").innerHTML = "<h1>Score :" + score;
});
}
game();
setInterval(game, 1000);
setTimeout(function ()
{alert("Your Score is " + score)
window.location.href = "startGame.html";
}, 16000);
</script>
</body>
</html>

Navigate a Table via the keyboard?

I'm trying to make a table that can do the following.
Row x Cols = 3x3: ok
Navigate via keyboard: ok
When 'focus' (or something) is on a cell update div2 with the data-param2: not working.
When pressing Enter on keyboard, update div1 with data-param1: not working
<html>
<head>
<title>arrows.htm</title>
<script language="javascript" type="text/javascript" src="js/keycode.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script type="text/javascript">
var b4 = "";
var col = 1;
var row = 1;
function bg() {
var rc = "r" + row + "c" + col;
if (b4 == "") b4 = rc;
document.getElementById(b4).style.backgroundColor = "white";
document.getElementById(rc).style.backgroundColor = "yellow";
b4 = rc;
}
function test(){
document.getElementById("q").innerHTML=this.id;
}
function processKeyDown(e) {
var keyCode;
if(e.which) { keyCode = e.which; }
else {
alert("Unknown event type.");
return ;
}
processKeyHandle(keyCode);
}
function processKeyHandle(keyCode) {
var nc = 0;
switch(keyCode) {
case VK_LEFT :
if (col > 1) col--;
bg();
break;
case VK_UP :
if (row > 1) row--;
bg();
break;
case VK_RIGHT :
if (col < 3) col++;
bg();
break;
case VK_DOWN :
if (row < 3) row++;
bg();
case VK_ENTER :
break;
}
}
</script>
</head>
<body onload="bg()" onkeydown="processKeyDown(event);" >
<div id="div1">test</div>
<div id="div2">test2</div>
<div>
<table border="1" id="tab">
<tr>
<td id="r1c1"><img class="imgs" height="100" width="50" class="e" data-param1="666" data-param2="777" src="http://web.scott.k12.va.us/martha2/dmbtest.gif" /></td>
<td id="r1c2">b0</td>
<td id="r1c3">c0</td>
</tr>
<tr>
<td id="r2c1">a1</td>
<td id="r2c2">b1</td>
<td id="r2c3">c1</td>
</tr>
<tr>
<td id="r3c1">a2</td>
<td id="r3c2">b2</td>
<td id="r3c3">c2</td>
</tr>
</table>
</div>
<script>
$(".imgs").click(function(){
var elmThis = $(this);
$("#div1").text(elmThis.data("param1"));
});
</script>
</body>
</html>
I got it to work
<html>
<head>
</head>
<body onload="bg()" onkeydown="processKeyDown(event);" >
<div id="div1">test</div>
<div id="div2">test2</div>
<div>
<table border="1" id="tab">
<tr>
<td id="r1c1" data-param1="r1c1 param1" data-param2="r1c1 param2">a0</td>
<td id="r1c2" data-param1="r1c2 param1" data-param2="r1c2 param2">b0</td>
<td id="r1c3" data-param1="r1c3 param1" data-param2="r1c3 param2">c0</td>
</tr>
<tr>
<td id="r2c1" data-param1="r2c1 param1" data-param2="r2c1 param2">a1</td>
<td id="r2c2" data-param1="r2c2 param1" data-param2="r2c2 param2">b1</td>
<td id="r2c3" data-param1="r2c3 param1" data-param2="r2c3 param2">c1</td>
</tr>
<tr>
<td id="r3c1" data-param1="r3c1 param1" data-param2="r3c1 param2">a2</td>
<td id="r3c2" data-param1="r3c2 param1" data-param2="r3c2 param2">b2</td>
<td id="r3c3" data-param1="r3c3 param1" data-param2="r3c3 param2">c2</td>
</tr>
</table>
</div>
<script language="javascript" type="text/javascript" src="js/keycode.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script type="text/javascript">
var b4 = "";
var col = 1;
var row = 1;
function bg() {
var rc = "r" + row + "c" + col;
if (b4 == "") b4 = rc;
$("#"+b4).css("backgroundColor","white");
$("#div2").text($("#"+rc).css("backgroundColor","yellow").data("param2"));
b4 = rc;
}
function processKeyDown(e) {
var keyCode;
if(e.which) {
keyCode = e.which;
} else {
alert("Unknown event type.");
return ;
}
processKeyHandle(keyCode);
}
function processKeyHandle(keyCode) {
var nc = 0;
switch(keyCode) {
case VK_LEFT :
if (col > 1) col--;
bg();
break;
case VK_UP :
if (row > 1) row--;
bg();
break;
case VK_RIGHT :
if (col < 3) col++;
bg();
break;
case VK_DOWN :
if (row < 3) row++;
bg();
break;
case VK_ENTER :
$("#div1").text($("#"+b4).data("param1"));
break;
}
}
</script>
</body>
</html>
It looks like you're using $.data() not html5 attributes data-yournamehere
If you want to set or access those, do:
$(this).attr('data-param', 'set-the-value-here');
To retrieve it, simply do $(this).attr('data-param');

Categories

Resources