What I've done: So I am creating a game of chess in Java Script, and I have an 8 by 8 board (html table) with pieces on the board. I have currently set up some Click Handlers to recognize what board spot the user has clicked on (each td has its own id 0-63, and using this.cellIndex and .rowIndex I can get the coordinates).
Problem: My code so far is working but I'm currently trying to figure out how to save two separate user inputs (one selecting the coordinates of the where the piece currently is, and the second where the user wants the piece to go). My idea was to pass the variable cellContent as a parameter from "selectPiece()" to "movePiece()" so that I could have both variables in the same funciton but I can't seem to get it to work. Any suggestions or other ideas?
My Code:
function addClickHandlers() {
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function selectPiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
var row = this.parentNode.rowIndex;
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
document.getElementById(this.id).style.backgroundColor = "blue";
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function movePiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
console.log(this.cellIndex);
var row = this.parentNode.rowIndex;
console.log(this.id);
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
console.log(cellContent);
document.getElementById(this.id).style.backgroundColor = "red";
};
}
var postCoordinates = document.createTextNode("You clicked on coordinates: (" + row + "," + col + ").");
coordinates.appendChild(postCoordinates);
var br = document.createElement("br");
coordinates.appendChild(br);
};
}
}
Snippet
function showBoard() {
var tr;
var td;
var check;
var i = 0;
var j = 0;
var cellId = 0;
var table = document.getElementById("myTable");
for(i = 0; i < 8; i++) {
tr = table.insertRow(i);
for(j = 0; j < 8; j++) {
td = tr.insertCell(j);
if(i%2 == 1)
{
if(j%2 == 1)
{
td.setAttribute("class", "black");
}
else
{
td.setAttribute("class", "white");
}
}
else
{
if(j%2 == 1)
{
td.setAttribute("class", "white");
}
else
{
td.setAttribute("class", "black");
}
}
cellId = (i * 8) + j;
td.setAttribute("id", cellId);
var content = getSquare(i, j);
if (content == "br") {
var blackRook = document.createElement("IMG");
blackRook.setAttribute("src", "chess-piece-black-rook.png");
td.appendChild(blackRook);
}
else if (content == "bk") {
var blackKnight = document.createElement("IMG");
blackKnight.setAttribute("src", "chess-piece-black-knight.png");
td.appendChild(blackKnight);
}
else if (content == "bb") {
var blackBishop = document.createElement("IMG");
blackBishop.setAttribute("src", "chess-piece-black-bishop.png");
td.appendChild(blackBishop);
}
else if (content == "bK") {
var blackKing = document.createElement("IMG");
blackKing.setAttribute("src", "chess-piece-black-king.png");
td.appendChild(blackKing);
}
else if (content == "bQ") {
var blackQueen = document.createElement("IMG");
blackQueen.setAttribute("src", "chess-piece-black-queen.png");
td.appendChild(blackQueen);
}
else if (content == "bp") {
var blackPawn = document.createElement("IMG");
blackPawn.setAttribute("src", "chess-piece-black-pawn.png");
td.appendChild(blackPawn);
}
else if (content == "wr") {
var whiteRook = document.createElement("IMG");
whiteRook.setAttribute("src", "chess-piece-white-rook.png");
td.appendChild(whiteRook);
}
else if (content == "wk") {
var whiteKnight = document.createElement("IMG");
whiteKnight.setAttribute("src", "chess-piece-white-knight.png");
td.appendChild(whiteKnight);
}
else if (content == "wb") {
var whiteBishop = document.createElement("IMG");
whiteBishop.setAttribute("src", "chess-piece-white-bishop.png");
td.appendChild(whiteBishop);
}
else if (content == "wK") {
var whiteKing = document.createElement("IMG");
whiteKing.setAttribute("src", "chess-piece-white-king.png");
td.appendChild(whiteKing);
}
else if (content == "wQ") {
var whiteQueen = document.createElement("IMG");
whiteQueen.setAttribute("src", "chess-piece-white-queen.png");
whiteQueen.setAttribute("id", "botImg");
td.appendChild(whiteQueen);
}
else if (content == "wp") {
var whitePawn = document.createElement("IMG");
whitePawn.setAttribute("src", "chess-piece-white-pawn.png");
td.appendChild(whitePawn);
}
}
}
addClickHandlers();
}
function addClickHandlers() {
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function selectPiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
console.log(this.cellIndex);
var row = this.parentNode.rowIndex;
console.log(this.id);
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
console.log(cellContent);
document.getElementById(this.id).style.backgroundColor = "blue";
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function movePiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
console.log(this.cellIndex);
var row = this.parentNode.rowIndex;
console.log(this.id);
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
console.log(cellContent);
document.getElementById(this.id).style.backgroundColor = "red";
};
}
var postCoordinates = document.createTextNode("You clicked on coordinates: (" + row + "," + col + ").");
coordinates.appendChild(postCoordinates);
var br = document.createElement("br");
coordinates.appendChild(br);
};
}
}
//Game state variables
var grid = [[ "br", "bk", "bb", "bK", "bQ", "bb", "bk", "br" ],
[ "bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp" ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ "wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp" ],
[ "wr", "wk", "wb", "wK", "wQ", "wb", "wk", "wr" ]];
var turn = 7;
var capturedWhite = [];
var capturedBlack = ["bp"];
var gameOver = false;
//Game state functions
function getSquare(row, col) {
return grid[row][col];
}
function pawnMove(start, finish)
{
}
table {
background-color: black;
}
td.white {
height: 65px;
width: 65px;
background-color: white;
}
td.black {
height: 65px;
width: 65px;
background-color: black;
hover {
background-color: white;
}
}
img {
height: 45px;
width: 45px;
padding: 10px;
}
td:hover {
background-color: blue;
}
body {background: #cba;}
#botDiv {position: relative; bottom: 0; left: 0; height: 65;}
#botImg {position: relative; bottom: 0; left: 0;}
<!DOCTYPE html>
<html>
<head>
<title>Game Grid</title>
<link rel="stylesheet" href="gameGridStyle.css">
</head>
<body onload="showBoard();">
<div id="botDiv">
</div>
<script src = "genTable.js"></script>
<script src = "model.js"></script>
<script src = "queenBot.js"></script>
<script src = "loadGame.js"></script>
<table id="myTable">
</table>
<p id="coordinates">
</p>
<label>Here is your user data: </label>
<div id="username"></div><br>
<div id="timestamp"></div>
<button id="logoutButton" onclick="logout()">Log-out</button><br><hr>
<div id="loadDataDiv"></div>
<button id="loadGame" onclick="loadData()">Load Game</button><br><hr>
</body>
</html>
Related
How can I get the chat to scroll to bottom when new content is sent into the chat? I'm trying to add something like this:
$('#what do I have to put here?').animate({scrollTop: $('#and here?').prop("scrollHeight")}, 200);
but I can't make it work (I have no idea where in the code to place it).
Thanks!
This is an important part of the code... Maybe I have to add it here (but I don't know how or where):
<script type="text/javascript">
var _answerBot = new answerBot();
function keypressInput(sender, event) {
if (event.which == 13) {
document.getElementById('subcontent').innerHTML += _answerBot.processInput(sender.value);
sender.value = '';
}
}
</script>
This is a separate scripts.js file:
var answerBot = function () {
var _this = this;
_this.processInput = function (text) {
updateUrl(text);
var _result = "<p class='answerbot-input'>" + text + "</p>";
text = text.replace(new RegExp("[ ]{2,}", "g"), " ");
var _words = text.toLowerCase().split(" ");
var _answers = [];
var _title = "";
if (_words.length === 0 || _words.toString() === '') { //if the input is empty
_answers = _this.specialContext.emptyInput;
_title = _this.specialContext.emptyInput;
} else {
var _possibleAnswers = findMatches(_words);
if (_possibleAnswers.length === 0) { //if no answer found
_answers = _this.specialContext.wrongInput;
_title = _this.specialContext.wrongInput;
}
if (_possibleAnswers.length == 1) { //context recognized
_answers = _this.answers[_possibleAnswers[0]].values;
_title = _this.answers[_possibleAnswers[0]].description;
}
if (_possibleAnswers.length > 1) {
_result += formatText(_this.specialContext.rephrase, _this.specialContext.rephrase);
for (var i = 0; i < _possibleAnswers.length; i++) {
_result += formatText(_this.answers[_possibleAnswers[i]].description, _this.answers[_possibleAnswers[i]].description);
}
}
}
if (_answers.length > 0) {
var _rand = Math.floor((Math.random() - 0.001) * _answers.length);
_result += formatText(_answers[_rand], _title);
}
return _result;
};
function formatText(text, title) {
return "<p class=\'answerbot-ai\' title=\'" + title + "\'>" + text + "</p>";
}
function findMatches(words) {
var foundKeywords = [];
var _possibleAnswers = [];
for (var i = 0; i < _this.keywords.length; i++) {
foundKeywords[i] = 0;
for (var j = 0; j < words.length; j++) {
if (_this.keywords[i].keys.indexOf(words[j]) >= 0) {
foundKeywords[i]++;
if (foundKeywords[i] == _this.keywords[i].keys.length) {
return [_this.keywords[i].value];
}
}
}
if (foundKeywords[i] * 2 > _this.keywords[i].keys.length) {
_possibleAnswers.push(_this.keywords[i].value);
}
}
return _possibleAnswers.filter(function (elem, pos) {
return _possibleAnswers.indexOf(elem) == pos;
});
}
function updateUrl(text){
history.pushState(null, null, "#question=" + encodeURIComponent(text));
if(typeof ga === "function")//google analytics
ga('send', 'event', 'question', text);
}
};
function AddMessage() {
var $message = $("<p>").text("message");
var $messages = $("#messages");
$messages.append($message);
$messages.animate({
scrollTop: $messages.prop("scrollHeight")
});
}
#messages {
border: 1px solid #000;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
<div id="messages"></div>
<button onClick="AddMessage()">Add Message</button>
</div>
When I hit my calculate button, the new lists with values pulled from the arrays are visible, but the second array is missing a value.The missing value is not always the same value. For example if I put in 1,2,3,4,5,6, it's not always the same number missing, it's probably the last value in the array, but I can't figure out where I went wrong. Here's the code:
$(document).ready(function() {
function copyarray(arraytocopy) {
var theCopy = []; // An new empty array
for (var i = 0, len = arraytocopy.length; i < len; i++) {
theCopy[i] = arraytocopy[i];
}
return theCopy;
}
function sortarray(arraytosort) {
arraytosort.sort(
function(a, b) {
return Math.round(Math.random());
}
);
return arraytosort;
}
function checkarrays(newarray, oldarray) {
var swappositions = [];
for (var i = 0; i < newarray.length; i++) {
if (newarray[i] == oldarray[i]) {
//alert(oldarray[i] + ' is the SAME!');
swappositions.push(newarray[i]);
}
}
var countsame = 0;
swappositions.reverse();
for (var i = 0; i < newarray.length; i++) {
if (newarray[i] == oldarray[i]) {
///alert(oldarray[i] + ' is the SAME!');
newarray[i] = swappositions[countsame];
countsame = countsame + 1;
}
}
for (var i = 0; i < newarray.length; i++) {
if (newarray[i] == oldarray[i]) {
//alert(oldarray[i] + ' is the SAME!');
//swappositions.push(newarray[i]);
var elementbefore = newarray[i - 1];
newarray[i - 1] = newarray[i];
newarray[i] = elementbefore;
}
}
///alert('test');
///alert('new array: ' + newarray);
///alert('old array: ' + oldarray);
//alert(swappositions.toString());
//alert($.inArray( swappositions[0], newarray ));
return true;
}
Array.prototype.randomize2 = function() {
var oldarray = copyarray(this);
sortarray(this);
var notthesame = checkarrays(this, oldarray);
if (notthesame = false) {
//alert('sort again');
sortarray(this);
notthesame = checkarrays(this, oldarray);
}
//alert('new: '+this);
//alert('old: '+oldarray);
//alert('not the same!');
return this;
};
function makelist(myarray) {
var list = '<ol>';
var listitem = '';
for (var i = 0; i < myarray.length; i++) {
if (/\S/.test(myarray[i])) {
listitem = '<li>' + $.trim(myarray[i]) + '</li>';
list += listitem;
}
}
list += '</ol>';
//alert(list.toString());
return list.toString();
}
function combinelists(ordered, random) {
var list = '<ol>';
var listitem = '';
for (var i = 0; i < ordered.length; i++) {
if (/\S/.test(ordered[i])) {
if ($.trim(random[i]) == $.trim(ordered[i])) {
listitem = '<li class="same"><span class="yourname">' + $.trim(ordered[i]) + '</span> is matched with<span class="peersname">' + $.trim(random[i]) + '</span></li>';
list += listitem;
} else {
listitem = '<li><span class="yourname">' + $.trim(ordered[i]) + '</span> is matched with <span class="peersname">' + $.trim(random[i]) + '</span></li>';
list += listitem;
}
}
}
list += '</ol>';
//alert(list.toString());
return list.toString();
}
$('#ranGen').click(function() {
//function randomize(){
var lines = $('#names').val().split(/\n/);
var texts = [];
for (var i = 0; i < lines.length; i++) {
// only push this line if it contains a non whitespace character.
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
var orderedlist = makelist(lines);
//$( "#list" ).html(orderedlist);
var linescopy = $.extend(true, [], lines);
var randomarray = linescopy.randomize2();
//alert(randomarray);
var randomlist = makelist(randomarray);
//$( "#randomlist" ).html(randomlist);
var combinedlists = combinelists(lines, randomarray);
$("#combined").html(combinedlists);
});
});
textarea {
height: 100px;
width: 400px;
}
input {
display: block;
}
.list {
display: inline-block;
}
.same {
color: orange;
}
.yourname {
color: blue;
}
.peersname {
color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Get a random match </h1>
<p>Insert all your names into the textarea below. Each name should be on a new line. Hit the button to generate your matches.</p>
<form>
<textarea id="names" placeholder="Enter list of names here. Each name should be on a new line."></textarea>
<input type="button" id="ranGen" value="Go" onClick="JavaScript:randomize()" />
</form>
<div id="list" class="list"></div>
<div id="randomlist" class="list"></div>
<div id="combined" class="list"></div>
Filtering out "empty" lines should fix the issue
var lines = $('#names').val().split(/\n/).filter(function (val) {
return val.trim() != '';
});
An extension of my previous calculators, its now time to look at the onChange or addEventListener functions to run my code without using the submit buttons.
I am having a hard time trying to figure out how I can have the event fire once either the 'H' or 'Extra Room Factor' fields have been changed. I only want the row that is being edited / changed to fire the event, not the entire table. I am trying to figure out how I can 'find' which row / cell is calling the function and then use it in the script to get the other values required.
The script uses JSON to get data which determines how the table is set out.
The code should get the values from L, W and H and multiply them together. It should then multiply the Extra Room Factor and write the result into the 'Total Room M3' field.
(No Rep to post images)
Uh, I have all my code in a fiddle but the current code relies on JSON to get the details. I can't post the fiddle link due to low rep!
jsfiddleFiddle Link
JSON File
Thanks!
function init() {
var url = "http://localhost/javascript/comcool/working/data.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.send(null);
request.onload = function () {
if (request.status === 200) {
result = JSON.parse(request.responseText);
drawMainTable();
drawTable2();
drawTable3();
}
rooms = result.numberOfRooms;
};
}
function drawMainTable() {
var div = document.getElementById("calc");
var drawTable = document.createElement("table");
drawTable.id = "calcTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("calcTable");
//Draw Location Field
for ( var i = 0; i < result.locations.length ; i++ ) {
if ( result.locations[i].name !== null) {
var locations = document.getElementById("location");
var option = document.createElement("option");
option.value = result.locations[i].name;
option.text = result.locations[i].name;
locations.appendChild(option);
}
}
//Create Head Elements
for ( var i = 0; i < result.titles.length; i++ ) {
var createHead = document.createElement("th");
createHead.innerHTML = result.titles[i].name;
table.appendChild(createHead);
}
//Create Row Elements
for ( var i = 0; i < result.numberOfRooms ; i++ ) {
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var roomInput = document.createElement("input");
roomInput.type = "text";
roomInput.id = "R" + i + "Name";
cell1.appendChild(roomInput);
var cell2 = row.insertCell(1);
var lInput = document.createElement("input");
lInput.type = "number";
lInput.id = "R" + i + "L";
lInput.className = "smallInput";
cell2.appendChild(lInput);
var cell3 = row.insertCell(2);
var wInput = document.createElement("input");
wInput.type = "number";
wInput.id = "R" + i + "W";
wInput.className = "smallInput";
cell3.appendChild(wInput);
var cell4 = row.insertCell(3);
var hInput = document.createElement("input");
hInput.type = "number";
hInput.id = "R" + i + "H";
hInput.onchange = calculateRoomM3;
hInput.className = "smallInput";
cell4.appendChild(hInput);
var cell5 = row.insertCell(4);
var extraRoomFactorInput = document.createElement("input");
extraRoomFactorInput.type = "number";
extraRoomFactorInput.id = "R" + i + "Factor";
extraRoomFactorInput.value = "1.0";
extraRoomFactorInput.step = "0.1";
extraRoomFactorInput.min = "1.0";
extraRoomFactorInput.max = "1.3";
cell5.appendChild(extraRoomFactorInput);
var cell6 = row.insertCell(5);
var m3Output = document.createElement("output");
m3Output.id = "R" + i + "M3Total";
cell6.appendChild(m3Output);
var cell7 = row.insertCell(6);
var suggDia = document.createElement("output");
suggDia.id = "R" + i + "Dia";
cell7.appendChild(suggDia);
var cell8 = row.insertCell(7);
var outSize = document.createElement("select");
outSize.id = "R" + i + "OutletSize";
cell8.appendChild(outSize);
for ( var x = 0; x < result.ductInfo.length ; x++ ) {
if ( result.ductInfo[x].ventSize != "nil") {
var option = document.createElement("option");
option.value = result.ductInfo[x].ventSize;
option.text = result.ductInfo[x].ventSize;
outSize.appendChild(option);
}
}
var cell9 = row.insertCell(8);
var ductDia = document.createElement("output");
ductDia.id = "R" + i + "DuctSize";
cell9.appendChild(ductDia);
}
}
function drawTable2() {
var p = document.getElementById("total");
var table = document.createElement("Table");
table.id = "totalTable";
table.className = "tg";
p.appendChild(table);
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++){
var tr = document.createElement('TR');
var outputBox = document.createElement("output");
var inputBox = document.createElement("input");
tableBody.appendChild(tr);
var td = document.createElement('TD');
if ( i === 0 ) {
td.appendChild(document.createTextNode("Total M3 All Rooms:"));
} else if ( i == 1 ) {
td.appendChild(document.createTextNode("Extra House Heat Load:"));
} else if ( i == 2 ) {
td.appendChild(document.createTextNode("Total System m3 Required:"));
}
tr.appendChild(td);
var td = document.createElement('TD');
if ( i === 0 ) {
outputBox.id = "HouseM3Total";
td.appendChild(outputBox);
} else if ( i == 1 ) {
inputBox.type = "number";
inputBox.id = "HouseHeatLoad";
inputBox.value = "1.0";
inputBox.step = "0.1";
inputBox.min = "1.0";
inputBox.max = "1.3";
td.appendChild(inputBox);
} else if ( i == 2 ) {
outputBox.id = "HouseAdjustM3Total";
td.appendChild(outputBox);
}
tr.appendChild(td);
}
}
function drawTable3() {
var div = document.getElementById("dropper");
//create table
var drawTable = document.createElement("table");
drawTable.id = "dropperTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("dropperTable");
//Create Head Elements
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
if ( i === 0) {
createHead.innerHTML = "";
} else if ( i === 1) {
createHead.innerHTML = "Dropper Duct Size";
} else if ( i === 2) {
createHead.innerHTML = "Dropper Duct Capacity";
}
table.appendChild(createHead);
}
for ( var i = 0; i < 6 ; i++ ) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var dropperName = document.createElement("output");
dropperName.innerHTML = "Dropper Duct Side " + [i + 1];
cell1.appendChild(dropperName);
var cell2 = row.insertCell(1);
var dropperInput = document.createElement("input");
dropperInput.type = "number";
dropperInput.id = "D" + [i] + "Size";
cell2.appendChild(dropperInput);
var cell3 = row.insertCell(2);
var dropperOutput = document.createElement("output");
dropperOutput.id = "D" + [i] + "Capacity";
cell3.appendChild(dropperOutput);
}
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var designCapacity = document.createElement("output");
designCapacity.colSpan = "2";
designCapacity.innerHTML = "Design Dropper Capacity";
cell1.colSpan = "2";
cell1.appendChild(designCapacity);
var cell2 = row.insertCell(1);
var DTotalCapacity = document.createElement("output");
DTotalCapacity.id = "DTotalCapacity";
cell2.appendChild(DTotalCapacity);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var modelCapacity = document.createElement("output");
modelCapacity.innerHTML = "Model Dropper Capacity";
cell1.colSpan = "2";
cell1.appendChild(modelCapacity);
var cell2 = row.insertCell(1);
var dropperCapacityUnit = document.createElement("output");
dropperCapacityUnit.id = "dropperCapacityUnit";
cell2.appendChild(dropperCapacityUnit);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var modelSelect = document.createElement("output");
modelSelect.innerHTML = "Model Selection";
cell1.colSpan = "2";
cell1.appendChild(modelSelect);
var cell2 = row.insertCell(1);
var model = document.createElement("output");
model.id = "model";
cell2.appendChild(model);
}
function startCalculate() {
getLocationValue = 0;
totalHouseM3 = 0;
findLocation();
calculateTotalM3();
calculateDuctDia();
findUnitSpecs();
return;
}
function dropperCalculate() {
calculateDropperDia();
finalUnitCalc();
}
function replaceWithDropdownModel( id , valueList ){
var element = document.getElementById( id );
var dropdown = document.createElement("select"),
value = element.value,
option;
dropdown.id = id;
for( var i = 0 ; i < valueList.length ; i++ ){
option = document.createElement("option");
option.text = valueList[i];
option.value = valueList[i];
if( option.value == value){
option.selected = true;
}
dropdown.options.add(option);
}
element.parentNode.replaceChild( dropdown , element );
}
function findLocation() {
var getLocationFactor = document.getElementById("location").value;
for ( var i = 0 ; i < result.locations.length ; i++) {
if (result.locations[i].name === getLocationFactor) {
getLocationValue = result.locations[i].factor;
}
}
}
function calculateTotalM3() {
for ( var i = 0; i < rooms ; i++ ) {
var roomL = document.getElementById("R" + i + "L").value,
roomW = document.getElementById("R" + i + "W").value,
roomH = document.getElementById("R" + i + "H").value,
roomFactor = document.getElementById("R" + i + "Factor").value,
ductDia = document.getElementById("R" + i + "Dia"),
calcM3 = Math.round((roomL * roomW * roomH) * roomFactor);
var outputRoomM3 = document.getElementById("R" + i + "M3Total");
outputRoomM3.innerHTML = calcM3;
totalHouseM3 = totalHouseM3 + calcM3;
var inputHouseHeatLoad = document.getElementById("HouseHeatLoad").value;
var outputHouseM3 = document.getElementById("HouseM3Total");
outputHouseM3.innerHTML = totalHouseM3 + " m3";
for ( var x = 0; x < result.ductInfo.length; x++) {
if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc1 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc1 && getLocationValue === 1) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc2 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc2 && getLocationValue === 2) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc3 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc3 && getLocationValue === 3) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc4 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc4 && getLocationValue === 4) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc5 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc5 && getLocationValue === 5) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
}
}
}
var totalHouseM32 = Math.round(totalHouseM3 * inputHouseHeatLoad);
var outputAdjHouseM3 = document.getElementById("HouseAdjustM3Total");
outputAdjHouseM3.innerHTML = totalHouseM32 + " m3";
}
function calculateDuctDia() {
for ( var i = 0; i < rooms ; i++ ) {
var outletSize = document.getElementById("R" + [i] + "OutletSize").value;
var outputDuctSize = document.getElementById("R" + [i] + "DuctSize");
var diaResult;
for ( var x = 0; x < result.ductInfo.length ; x++) {
if (result.ductInfo[x].ventSize == outletSize) {
diaResult = result.ductInfo[x].ventSize;
}
}
outputDuctSize.innerHTML = diaResult;
}
}
function findUnitSpecs() {
unitArray = [];
for ( var x = 0 ; x < result.modelFinder.length; x++) {
if (totalHouseM3 <= result.modelFinder[x].location1Capacity && getLocationValue === 1) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location2Capacity && getLocationValue === 2) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location3Capacity && getLocationValue === 3) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location4Capacity && getLocationValue === 4) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location5Capacity && getLocationValue === 5) {
unitArray.push(result.modelFinder[x].model);
}
replaceWithDropdownModel( "model" , unitArray);
}
return [
unitArray
];
}
function calculateDropperDia() {
totalDropperCapacity = 0;
dropperSides = 6;
for ( var i = 0; i < dropperSides ; i++ ) {
var dropperSize = document.getElementById("D" + i + "Size").value,
outputDropperCapacity = document.getElementById("D" + i + "Capacity");
var dropperResult;
for ( var x = 0; x < result.ductInfo.length ; x++) {
if (result.ductInfo[x].ductSize == dropperSize) {
dropperResult = result.ductInfo[x].dropperCapacity;
} else if (dropperSize > 551) {
dropperResult = "Size Does Not Exist";
}
}
outputDropperCapacity.innerHTML = dropperResult;
var dropperCapacityElement = document.getElementById("DTotalCapacity");
totalDropperCapacity = totalDropperCapacity + dropperResult;
dropperCapacityElement.innerHTML = totalDropperCapacity;
}
}
function finalUnitCalc() {
var selectedUnit = document.getElementById("model").value,
dropperCapacityUnit = document.getElementById("dropperCapacityUnit");
for ( var i = 0 ; i < result.modelFinder.length ; i++) {
if (selectedUnit === result.modelFinder[i].model) {
dropperCapacityUnit.innerHTML = result.modelFinder[i].dropperCapacity;
}
}
}
window.onload = init;
function calculateRoomM3() {
// iterate through all current rows and get the values of each, save it as a variable in each and then calculate
//
var table = document.getElementById("calcTable");
var rowCount = table.rows[0].cells[1].childNodes[0].value;
console.log(rowCount);
// var roomL =
// roomW =
// roomH =
// roomFactor =
// roomTotal =
// var thisID = document.getElementById(thisID).value,
//thisW = document.getElementById(thisW).value,
//thisL = document.getElementById(thisL).value,
//thisFactor = document.getElementById(thisFactor).value,
//thisTotal = document.getElementById(thisTotal);
//var roomM3 = Math.round((thisL * thisW * thisID)) * thisFactor;
//thisTotal.innerHTML = roomM3;
//console.log(thisID);
//console.log(thisW);
//console.log(thisL);
//console.log(roomM3);
}
#calc{
width: 850px;
margin-bottom: 1em;
}
div {
border: 1px solid white;
}
#dropper {
width: 400px;
position: absolute;
margin-left: 875px;
}
#total {
clear: both;
}
#button2 {
position:absolute;
margin-left: 875px;
margin-top: -250px;
}
h1 {
text-align: center;
}
p {
text-align: center;
}
input {
text-align: center;
}
.tg {
border-collapse:collapse;
border-spacing:0;
text-align: center;
}
.tg td{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
}
.tg th{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
vertical-align: top;
}
.tg .tg-s6z2{
text-align:center
}
.smallInput {
width: 50px;
text-align: center;
}
.factors {
text-align: center;
width: 80px;
}
.factors2 {
text-align: center;
width: 150px;
}
.tg2 {
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
border-top-color: #FFF;
border-right-color: #FFF;
border-bottom-color: #FFF;
border-left-color: #FFF;
}
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="ComCool.js" type="text/javascript"></script>
<meta charset="utf-8">
</head>
<body>
<form>
<div id="dropper">
<h1>Dropper Duct Calculator</h1><br>
<br>
</div>
<div id="calc">
<h1>Calculator</h1>
<p>Location: <select id="location">
</select></p>
</div>
</form>
<div id="total"></div>
<br/>
<div id="button2">
<input onclick="startCalculate()" type="button" value=
"1. Calculate M3, Diameter (Suggested and Actual)">
<br/></br>
<input onclick="dropperCalculate()" type="button" value=
"2. Calculate Dropper"><br>
</div>
<br>
</body>
</html>
I solved this for now by getting the entire ID of the current cell the event runs from, then splicing to get the ID scheme that I have through the table.
var str = this.id,
slice = str.slice(0,2),
roomL = slice + "L",
roomW = slice + "W",
roomH = slice + "H",
roomFactor = slice + "Factor",
roomTotal = slice + "M3Total",
roomDuctDia = slice + "Dia",
Its a quick solve, but it works!
This HTML and Javascript combined are supposed to form bars that are the height of the numbers entered in the prompt, relative to each other. The bars are not appearing when the numbers are entered. What do I need to fix in my code in order to make the bars appear?
"use strict";
window.onload=function()
{
var userValue;
var i;
var j;
var k;
var error;
var correct;
j = 0;
k = 0;
error = new Array(j);
correct = new Array(k);
userValue = window.prompt("Insert values separated by comma, whitespace, or both.");
userValue = packArray(trimElements(toArray(userValue, " ,")));
for(i = 0; i < userValue.length; i++)
{
if(isNumeric(userValue[i]) === false)
{
error[j] = userValue[i];
j = j + 1;
}
else
{
correct[k] = userValue[i];
k = k + 1;
}
}
if(error.length > 0)
{
window.alert("Error: " + error);
}
else
{
createGraph(userValue, document.getElementById("positiveQuadrant"));
}
};
function toArray(data, delimiters)
{
var locArray;
var result;
var i;
var dataArray;
var start;
locArray = findPositions(data, delimiters);
result = "";
i = 0;
if(data === null)
{
data = "";
}
else
{
result = result + data;
}
if(delimiters === null)
{
delimiters = "";
}
else
{
result = result + delimiters;
}
if(delimiters.length === 0)
{
delimiters = delimiters + " \t\r\n\f";
}
dataArray = new Array(locArray.length + 1);
start = 0;
while(i < dataArray.length)
{
dataArray[i] = data.substring(start, locArray[i]);
start = locArray[i] + 1;
i = i + 1;
}
return dataArray;
}
function findPositions(someString, lookForThis)
{
var i;
var result;
var count;
result = new Array(count);
i = 0;
count = 0;
while(i < someString.length)
{
if(lookForThis.indexOf(someString.charAt(i)) >= 0)
{
result[count] = someString.indexOf(lookForThis.charAt(i), (i + 1) - 1);
count = count + 1;
}
i = i + 1;
}
return result;
}
function trimElements(array)
{
var i;
var trimArray;
trimArray = new Array(array.length);
i = 0;
while(i < array.length)
{
trimArray[i] = trim(array[i]);
i = i + 1;
}
return trimArray;
}
function packArray(array)
{
var i;
var count;
var packedArray;
i = 0;
count = 0;
packedArray = new Array(count);
while(i < array.length)
{
if(array[i] !== null && array[i] !== "")
{
packedArray[count] = array[i];
count = count + 1;
}
i = i + 1;
}
return packedArray;
}
function convertToNumber(array)
{
var i;
var result;
i = 0;
result = "";
while(i < array.length)
{
if(isNumeric(array[i]) === true)
{
array[i] = Number(array[i]);
}
else
{
result = result + " " + array[i];
}
i = i + 1;
}
return trim(result);
}
function trim(data)
{
var start;
var whitespace;
var end;
var result;
if(typeof data==="string")
{
whitespace=" \n\r\t\f";
start=0;
}
else
{
result=data;
}
while((start<data.length)&&(whitespace.indexOf(data.charAt(start))))
{
start=start+1;
};
end=data.length-1;
while((end>=0)&&(whitespace.indexOf(data.charAt(end))))
{
end=end-1;
};
if(end<start)
{
result="";
}
else
{
result=data.substring(1+start,end);
}
return result;
};
function createHTMLElement(elementType, id, classInfo, content)
{
if(elementType===null)
{
elementType="";
};
trim(elementType);
if(id===null)
{
id="";
}
trim(id);
if(id.length>0)
{
id=" "+"id="+'"'+id+'"'+" ";
};
if(classInfo===null)
{
classInfo="";
}
trim(classInfo);
if(classInfo.length>0)
{
classInfo=" "+ "class="+'"'+classInfo+'"';
}
if(content===null)
{
content="";
};
trim(content);
return '<' +elementType +
id + classInfo +
'>' + content +
'</' + elementType + '>';
};
function isNumeric(data)
{
return isNaN(data);
};
function getRandomInteger(upperLimit)
{
return Math.floor(Math.random()*(upperLimit+1));
};
function getRandomRGB()
{
var blue;
var green;
var red;
red=getRandomInteger(255);
blue=getRandomInteger(255);
green=getRandomInteger(255);
return"rgb("+red+","+green+","+blue+")";
};
function createScaledArray(array, scaleFactor)
{
var i;
var scaledArray;
scaledArray = new Array(array.length);
for(i = 0; i < array.length; i++)
{
scaledArray[i] = (array[i] / scaleFactor);
}
return scaledArray;
}
function createGraph(array, quadReference)
{
var i;
var loc;
var scaleFactor;
var scaleArray;
var html;
var element;
var elementTop;
if(array.length > 0)
{
loc = 0;
for(i = 0; i < array.length; i++)
{
if(Number(array[i]) > Number(array[loc]))
{
loc = i;
}
}
scaleFactor = Math.abs(array[loc]);
scaleArray = createScaledArray(array, scaleFactor);
html = "";
for(i = 0; i < scaleArray.length; i++)
{
html = html + createHTMLElement("div", "columnContainer", "columnContainer", createHTMLElement("div", "coloredArea" + i, "coloredArea", createHTMLElement("div", "dataValue", "dataValue", array[i])));
}
quadReference.innerHTML = html;
for(i = 0; i < scaleArray.length; i++)
{
element = document.getElementById("coloredArea" + i);
elementTop = (100 - (scaleArray[i] * 100));
if(elementTop > 100)
{
elementTop = elementTop + (scaleArray[i] * 100);
}
element.style.top = elementTop + "%";
element.style.height = Math.abs(scaleArray[i] * 100) + "%";
element.style.backgroundColor = getRandomRGB();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Graphing </title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<script src="Graphing.js" type="text/javascript"></script>
<style type="text/css">
{
border : 0;
margin : 0;
padding : 0;
}
body
{
font-family : "Times New Roman", serif;
font-size : 12pt;
}
.positiveQuadrant
{
height:12em;
width:2em;
border-right:solid black 3px;
}
.negativeQuadrant
{
position:relative;
height:2em;
width:22em;
border-top:solid black 3px;
bottom:2em;
}
.columnContainer
{
position: relative;
float: left;
height: 10em;
width: 1.5em;
margin: 1px;
}
.coloredArea
{
position: relative;
background-color: red;
}
.dataValue
{
font-size: 12pt;
text-align: center;
position: relative;
top: -16px;
}
</style>
</head>
<body>
<div class ="positiveQuadrant" id="positiveQuadrant"></div>
<div class = "negativeQuadrant" id ="negativeQuadrant"></div>
</body>
</html>
I am trying to make a chess game. So far i have only made the white pawns moveable (you move them by dragging them to where you want them to go). However, only the first move works. Why does this happen? I use
$(".piece").mousedown(function(){}
, but it is only called once.
The problem is $("#" + tileFn).append($("#" + tileIn).html()); which creates a new piece element, to whom the mousedown handler is not attached.
One solution is to use event deletagation, or instead of creating a new element just move the existing element like
function parent(element) {
var parentID = $(element).parent().attr("ID");
var parentClass = $(element).parent().attr("class");
var parentType = $(element).parent().get(0).nodeName;
if (parentID != null) {
return ("#" + parentID);
} else if (parentClass != null) {
return ("." + parentClass);
} else {
if (parentType.toLowerCase() == "body") {
parentType = document;
return parentType;
} else {
return parentType;
}
}
}
var dimensions = 600; // must be divisible by 8
var tile1 = "<div class='tile tile1' id='";
var tile2 = "<div class='tile tile2' id='";
var end = "'></div>";
var multiplicity = "";
var tileIn = "";
var tileFi = "";
var classes = "";
var color = "";
var type = "";
var possible = [];
$(document).ready(function() {
//setup start
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
row = i * 2 + 1;
column = j * 2 + 1;
$("#container").append(tile1 + row + column + end + tile2 + row + (column + 1) + end);
}
for (var k = 0; k < 4; k++) {
row = i * 2 + 2;
column = k * 2 + 1;
$("#container").append(tile2 + row + column + end + tile1 + row + (column + 1) + end);
}
}
$("#container").css({
height: dimensions,
width: dimensions
});
$(".tile").css({
height: dimensions / 8,
width: dimensions / 8
});
$(".piece").css({
height: dimensions / 8,
width: dimensions / 8
});
$("<div class='b p piece'><img src='bp.icns' height='69'></div>").appendTo("#21, #22, #23, #24, #25, #26, #27, #28");
$("<div class='b r piece'><img src='br.icns' height='69'></div>").appendTo("#11, #18");
$("<div class='b n piece'><img src='bn.icns' height='69'></div>").appendTo("#12, #17");
$("<div class='b b piece'><img src='bb.icns' height='69'></div>").appendTo("#13, #16");
$("<div class='b k piece'><img src='bk.icns' height='69'></div>").appendTo("#14");
$("<div class='b q piece'><img src='bq.icns' height='69'></div>").appendTo("#15");
$("<div class='w p piece'><img src='wp.icns' height='69'></div>").appendTo("#71, #72, #73, #74, #75, #76, #77, #78");
$("<div class='w r piece'><img src='wr.icns' height='69'></div>").appendTo("#81, #88");
$("<div class='w n piece'><img src='wn.icns' height='69'></div>").appendTo("#82, #87");
$("<div class='w b piece'><img src='wb.icns' height='69'></div>").appendTo("#83, #86");
$("<div class='w q piece'><img src='wq.icns' height='69'></div>").appendTo("#84");
$("<div class='w k piece'><img src='wk.icns' height='69'></div>").appendTo("#85");
//setup end
$(".piece").mousedown(function() {
tileIn = parent($(this)).substr(1, 2);
classes = $(this).attr("class");
color = classes.charAt(0);
type = classes.charAt(2);
y = tileIn.charAt(0);
x = tileIn.charAt(1);
//white start
if (color == "w") {
//white pawn start
if (type == "p") {
if (y == "7") {
possible = ["6" + x, "5" + x];
} else {
possible = [(y - 1) + x];
}
return;
}
//white pawn end
//
else if ("a" == "b") {
}
}
//white end
//black start
else {
}
//white end
});
$(".tile").mouseup(function() {
tileFn = $(this).attr("id");
if (jQuery.inArray(tileFn, possible) !== -1 && $(this).is(':empty')) {
$("#" + tileFn).append($("#" + tileIn).contents());
} else {}
possible = [];
});
});
* {
user-drag: none;
-moz-user-select: none;
-webkit-user-drag: none;
}
#container {
margin: 0 auto;
border: 1px solid gray;
}
.tile {
float: left;
}
.tile1 {
background-color: white;
}
.tile2 {
background-color: rgba(0, 0, 0, 0.58);
}
.piece {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css">
<div id="container"></div>
The selector $(".piece") only selects the fields which has pices on it at the time you execute the statement. You will have to add the function to the fields as the pieces are moved on the board.
So you mouseup function should probably set the call back for the piece on the new field.