Cant understand why doesn't this javascript work - javascript

<!DOCTYPE html>
<html>
<head>
<title>Anti Chess</title>
</head>
<body>
<h1 id="game_title">Anti Chess by theManikJindal</h1>
<br />
<br />
<table id="game"></table>
<script>
var white = 1;
var ta = document.getElementById("game");
if(white == 1)
{
for(var i=0;i<8;i++)
{
var x = document.createElement('tr');
ta.appendChild(x);
for(var j=0;j<8;j++)
{
var y = document.createElement('td');
ta.childNodes[i].appendChild(y);
ta.childNodes[i].childNodes[j].setAttribute("id",String.fromCharCode(j+97)+(8-i).toString());
}
}
}
else
{
for(var i=0;i<8;i++)
{
var x = document.createElement('tr');
ta.appendChild(x);
for(var j=0;j<8;j++)
{
var y = document.createElement('td');
ta.childNodes[i].appendChild(y);
ta.childNodes[i].childNodes[j].setAttribute("id",String.fromCharCode(104-j)+(i+1).toString());
}
}
}
</script>
</body>
</html>
I cannot understand why this script is not working. Are there any good debuggers for Javascript or does one have to keep on smashing their heads against the wall to make some sense.
Please help
The script is supposed to create a table with 8x8 boxes and the attribute id should be set from "a8","b8","c8"..."h8" to "a1","b1","c1"..."h1" . for a when the value of white is 1. And from "h","g1","f1"..."a1" to "h8","g8",..."a8" for white not equal to 1. white =1 is default for now.

Tables must always have at least one <tbody> element. If it does not, the browser will create one.
This means that your entire childNodes access is wrong.
I would suggest this HTML:
<table><tbody id="game"></tbody></table>
That should make your code work, but you can simplify it further:
var white = 1, a = "a".charCodeAt(0), i, j, x, ta = document.getElementById("game");
for(i=0;i<8;i++) {
x = document.createElement('tr');
for(j=0;j<8;j++)
x.appendChild(document.createElement('td')).id =
String.fromCharCode((white == 1 ? j : 8-j)+a)+(white == 1 ? 8-i : i+1);
ta.appendChild(x);
}
As you can see I have eliminated the need for the entire block of code to be repeated, by moving the white == 1 check to the most relevant place. I have also made more use of the x reference, and I have replaced the "magic" values with something that will be easier to understand when you come back to it later (the a variable).
Hope this helps!
EDIT: Also, I just noticed that the table has no content - is this what you mean by it not showing up? Make sure you have suitable CSS to make the table cells visible.

This script is working fine. I have inspcted element in jsfiddle and found that elements are created.
I have used some css to show that boxes have been created.
css
table{
border:1px solid black;
}
table tr, td{
border:1px solid black;
}
see here http://jsfiddle.net/9uHPx/

Java script is working but table is not display.
Add border=1 in Table

Script is working fine. Added a couple loops so the ID will print to in the td tag so you can see what's going on. http://jsfiddle.net/5YRKx/
var tableTemp = document.getElementById("game");
for (var ii = 0, row; row = tableTemp.rows[ii]; ii++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
row.cells[j].innerHTML = row.cells[j].id;
}
}

Related

Javascript/html game using columns and rows

so I've been working on this for a few days now. This is what the game is supposed to do:
Using HTML, CSS, JavaScript, jQuery, or Angular code create a matrix 10 X 10 with columns/lanes using numbers and rows using letters to identify the cells. There will be two vehicles that randomly select a cell on the grid for placement. Randomly place ball target (the to acquire) somewhere on the grid. Have the vehicles check each column lane looking for the target. Once all cells have been checked in that lane have them move to another fresh lane that has not been checked. Keep a timer running to show time to acquire the target.
So far I was able to code the grid and the timer. So, what I need help doing, is placing a target/ball on the grid that is static, and then two finders/vehicles are then randomly placed on the grid.Going from left to right, they step through to the next column, until one of the cars is in the same column as the ball. There is a timer that sees how long it takes for one vehicle to land in same column as the ball.
<!DOCTYPE html>
<html>
<head>
<title>Soccer Ball Game</title>
<style>
button {
font-size:40px;
height:50px;
width:50px;
}
.cars{
background-color: green;
}
</style>
</head>
<body onload="createButtons(row, col)">
<div id="buttonArea">
</div>
<input type="button" id="btnNewGame" onClick="findBall()" value="ResetButtons"/></input>
<script>
var col = 10;
var row = 10;
var dCheck = true;
function createButtons(row,col){
var counter = 1;
var element = document.getElementById("buttonArea");
for(countR = 1; countR <= row; countR++){
for(countC = 1; countC <= col; countC++){
var newButton = document.createElement("button");
newButton.setAttribute("id", "btn" + counter);
newButton.setAttribute("type", "button");
newButton.setAttribute("class", "noclass");
element.appendChild(newButton);
counter++;
}
var breakLine = document.createElement("br");
element.appendChild(breakLine);
}
}
function resetButtons(){
var buttons = document.getElementsByTagName("button");
for(var i = 0; i < (buttons.length); i++){
buttons[i].innerHTML = "";
buttons[i].disabled = false;
buttons[i].setAttribute("class", "noclass");
}
}
</script>
</body>
</html>
And here is a timer code:
let timer={};
timer.counter=0;
timer.start=()=>{
timer.ticker=setInterval(()=>{ timer.counter++; },1000);
};
timer.stop=()=>{
clearInterval(timer.ticker);
};
let checker=(callback)={
timer.start();
//check each row in column
//if hit timer.stop();
callback(timer.counter);
};
checker((count)=>{
console.log('it took '+count+' second to hit target');
});
There are a lots of ways that you can use to place a target/ball on the grid buttons, For example, you can use CSS class trick like this:
.ball{
background: URL(ball.png);
}
And then add it to one of your buttons randomly. And for cars, you can use the same trick.
I hope this will help you a little bit but if you something else please correct me.

Creating a table of divs

I want to create a 16*16 table in html that holds div container in each cell. I'm not sure to what degree I'm allowed to mix jquery and pure javascript but what I have is
$( document ).ready(function() {
var table = Doucument.getElementById('table');
for (var i = 0; i <16; i++) {
var row = table.insertRow(i);
for(var j = 0; j < 16; j++){
row.insertCell(i);
}
};
});
This is adding a row to my table and then adding 16 cells. However I'm not sure how to add the div element to each cell. Perhaps theres a simpler way to do this with jquery? I'm not so proficient in jquery
Change "Document" to "document", remove the loop indexes (i, j) from the insertRow() and insertCell methods, and capture the newly inserted cell so that you can populate it. I've set each div's ID to be a combination of row and cell number in the example below.
I should also point out that there are better ways to do this. Tables should only be used for displaying data that requires tables. Also, this kind of thing would ideally be done on the server side unless there's a reason for you to do it in JavaScript.
That being said, here is a working example using JavaScript:
HTML:
<table id="myTable"></table>
JavaScript:
$(document).ready(function () {
var table = document.getElementById('myTable');
for (var i = 0; i < 16; i++) {
var row = table.insertRow();
for (var j = 0; j < 16; j++) {
var cell = row.insertCell();
var id = 'r' + i + 'c' + j;
cell.innerHTML = '<div id="' + id + '">' + id + '</div>';
}
};
});
CSS (after reading your comment about controlling size):
#myTable TD DIV {
height: 30px;
width: 30px;
}
Demo: http://jsfiddle.net/BenjaminRay/ugm613zg/
Do you have a specific reason to create a "table" - it is frowned upon by UX and CSS experts. It is considered a better approach to consider creating a table-like layout using Div/Spans and CSS. There are frameworks available that can provide you this layout style out of the box.
One of the most popular ones is Bootstrap's Grid - and here are some layout examples - http://getbootstrap.com/examples/grid/. The benefit of using this approach instead of tables is that your layout will adjust better to screen size changes like say viewing on a mobile device (called responsive layout).
In the interest of full disclosure Bootstrap supports 12 columns out of the box - but modifications are available for 16 and 24 columns - How to use bootstrap with 16 or 24 columns.
This is a longer route but a better solution than tables overall.
And using jQuery, you could do the following.
function addElems(ele, howMany, append) {
var $items = $();
for (var i = 0; i < howMany; i++) {
var $ele = $("<" + ele + "/>");
typeof append !== "undefined" && $ele.append(append);
$items = $items.add($ele);
}
return $items;
}
var $table = $("#myTable").append("<tbody></tbody>");
var $trs = addElems('tr', 16);
$table.append($trs);
$table.find("tbody > tr").each(function() {
var $tds = addElems('td', 16, "<div>My Div</div>");
$(this).append($tds);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable"></table>

Change color for every second ul li with a "for loop"

I am learning javascript in codecademy and so far I understand how alot of things work. Sadly they dont explain how to target an elements color or how to target elements / selectors / divs.
I am testing out my knowledge. What I am trying is to give every second list item the color red by using the for loop.
How do I do this?
var listColor = function(){
var color = style.("red");
var list = getElementsByTagName("li");
for (i = 0; i < list.length; i + 2;) {
list === color
}
];
listColor();
and here my http://jsfiddle.net/Lr8nZ/15/
UPDATED JSfiddle but still not working http://jsfiddle.net/Lr8nZ/23/
so basically:
Red,
Black,
Red,
Black
Something do like this.
var listColor = function(){
var list = document.getElementsByTagName("li");
for (i = 0; i < list.length; i++) {
if(i%2==0)
list[i].style="color:red";
else
list[i].style="color:blue";
}
}
listColor();
You have a few syntax errors, but you can do this:
var listColor = function() {
var list = document.getElementsByTagName('li');
for (var i = 0, l = list.length; i < l; i++) {
if (i % 2 === 0) {
list[i].style.color = 'red';
}
}
};
// Or...
var listColor = function() {
var list = document.getElementsByTagName('li');
for (var i = 0, l = list.length; i < l; i += 2) {
list[i + 1].style.color = 'red';
}
};
listColor();
When you increment i make sure you're updating its value with i++ or i += 1, or you'll create an endless loop.
i % 2 uses the % modulus operator. It's the remainder you would get from dividing the two numbers. Even numbers divide evenly by 2, so the remainder will be 0, which we check for.
The property you were looking for is called style. It has a property called color which we set to the string 'red' in this case.
try this
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
index=1;
$("#temp li").each(function(){
if(index%2==0)
{
$(this).css("color","red")
}
index++;
});
})
</script>
<style>
</style>
</head>
<body>
<ul id='temp'>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
</body>
</html>
Try using a console to see the errors in your code. It's a tool that's indispensible for any js coder. Here's the updated fiddle http://jsfiddle.net/Lr8nZ/24/
The first thing which you notice is style.color('red'). For this line to be even valid js, there has to be a style object defined. Otherwise it will search for it on window which always leads to confusion.
Another thing is note how we have to actually assign the new value to i in for loop' third condition. Just mentioning i+2 will not work because i will stay the same resulting in an infinite loop.
Again, fire up web console. Generally, you do that by right clicking on page > Inspect > Web console.

par.rowIndex is null in this code

I'm really new to JavaScript but I can't find out why this program won't work.
I want when I click the dynamically created button which is situated in a cell in my dynamically created table to get the rowindex of the row in which the button is situated.
Thanks in advance - here is my code:
<html>
<head>
<script>
function whichrow(obj) {
var par = obj.parentNode;
while(par.nodeName.toLowerCase()! = 'tr') {
par = par.parentNode;
}
alert(par.rowIndex);
}
</script>
</head>
<body>
<script>
mybody = document.getElementsByTagName("body")[0];
mytable = document.createElement("table");
mytablebody = document.createElement("tbody");
for(var i = 0; i<5; i++) {
mycurrent_row = document.createElement("tr");
mycurrent_row.id = "row"+i;
for(var j = 0; j<4; j++) {
mycurrentcell = document.createElement("td");
currenttext = document.createTextNode("Row" + i + "Column" + j);
mycurrentcell.appendChild(currenttext);
mycurrent_row.appendChild(mycurrentcell);
}
mybutoncell = document.createElement("td");
but = document.createElement("button");
mybutoncell.appendChild(but);
mycurrent_row.appendChild(mybutoncell);
mytablebody.appendChild(mycurrent_row);
but.onClick = whichrow(this);
}
mytable.appendChild(mytablebody);
mybody.appendChild(mytable);
mytable.setAttribute("border", "2");
</script>
</body>
</html>
Ok, so a few points to note here.
In the javascript eventing system, the system calls your callback with its own event object containing different properties according to what happened.
So, here are the mistakes:
When you're assigning to the event handler, when you say but.onclick = whichrow(this) you're setting but.onclick to the result of whichrow, which is undefined since you're not returning anything anyway. It should be but.onclick = whichrow; which will call whichrow when the user clicks your button. The parameter passed is a MouseEvent object. The link I've supplied should serve as a good start to read up on what kind of properties are available to you.
I have to check, since I use el.addEventListeners a lot, but onclick needs to be in lower case, not camelCase like you've done.
Inside the event callback, this usually refers to the element that was clicked, so you should use that.
There is no rowIndex property.
Now, trying to find a solution to your problem. rowIndex can be gleaned by traversing the dom. I'm not sure what purpose this will serve since you're creating the DOM by hand anyway and know the rowIndex already, but if it were unknown, here's what I would do
function whichRow(e) {
// here this should be the button.
var curRow = this.parentElement.parentElement,
rowIndex = 0;
while(curRow) {
curRow = curRow.previousElementChild;
rowIndex++;
}
return rowIndex;
}
I'm writing this off the top of my head, but the point is to give the main idea. In the above snippet, I've taken the parent of the parent of the button, since here's the approximate markup of the button section:
<tr>
<td>
<button></button>
</td>
</tr>
so, the parentElement of the parentElement of the button element should give you the <tr>. Then we'll traverse backwards till we don't have any previous elements, counting as we go. Once the previous element is null, return the count.
The obj you are passing to whichrow() is a button, which I assume inside a TD. So your while loop will exit in its first iteration itself, resulting in par holding a TD - which does not have a property named rowIndex

Generating random divs multiple times on load

let me just give a quick story. I have made a page. (VERY simple - two divs with a different background image, see here.)
Anyway, I need to make it so that when a new page loads, the two divs that I have load in a random order over and over, filling the entire screen content. So there's no pattern of the first div and then the second, it's just randomly generated. Sort of like a huge grid, with the two divs repeated with no pattern.
My question is...is that possible? I assume I'd need to know PHP, but I have no knowledge of it.
Thanks guys, I appreciate all help!
http://jsfiddle.net/uYPRq/
jquery
var div1 = '<div class="one">';
var div2 = '<div class="two">';
var len =
Math.floor(window.innerWidth/30)*Math.floor(window.innerHeight/30);
for (x = 0; x < len; x++) {
if ( Math.random() > 0.5 ) {
$(div1).appendTo('body');
}
else {
$(div2).appendTo('body');
}
}
css
div.one, div.two {
height:30px;
width:30px;
float:left;
}
div.one { background-color:#EBE1E4; }
div.two { background-color:#F0F5DF; }
edit:
changed screen.availWidth to window.innerWidth
Something like so? Just loop through how ever many times you like and add elements in.
for (i = 0; i < 300; i++) {
var type1 = document.createElement("div");
var type2 = document.createElement("div");
type1.innerHTML = "div1";
type2.innerHTML = "div2";
type1.setAttribute("class", "type1");
type2.setAttribute("class", "type2");
document.body.appendChild(type1);
document.body.appendChild(type2);
}
No PHP needed. This can be done client-side using Javascript (Jquery might be easier).

Categories

Resources