Allowing different widths of columns in rows - javascript

I am trying to get the table columns to have different widths on each row. I'm using an array to get the values which I am turning into width percentages and passing it into the column. The output seems to copy the row above even though it has different widths.
http://jsfiddle.net/0182rutf/2/
HTML
<table border='1' id="table">
JS
var Array = [
[10, 5, 10],
[50, 2, 10]
];
for (var k = 0; k < Array.length; k++)
{
var totalCol = 0;
$.each(Array[k], function (){totalCol += parseInt(this);});
$('#table').append('<tr id="' + k + '"></tr>')
for (var i = 0; i < Array[k][i]; i++)
{
var weight = Array[k][i];
var width = weight * 100 / totalCol;
$('#' + k).append('<td width="' + width + '%">column</td>');
}
}
Any idea how to fix this?

So as a followup for my comment above.
I would suggest going with flexbox here. But since you know the width of every column you want to draw you can also go without it and still keep IE9 support.
What I am doing here is simply having a div#grid acting as a package for your "table". Then with the JS I generate a div.row kind of like you generated the tr elements and in those I generate the div.cell elements like you would have done with the td elements and set the width directly on those "cells".
I changed your snippet to work:
http://jsfiddle.net/0182rutf/5/
CSS:
#grid {
border: 1px solid black;
}
#grid .row {
position: relative;
}
#grid .cell {
display: inline-block;
box-sizing: border-box;
border: 1px solid green;
}
JS:
var Array = [
[10, 5, 10],
[50, 2, 10]
];
for (var k = 0; k < Array.length; k++)
{
var totalCol = 0;
$.each(Array[k], function (){totalCol += parseInt(this);});
$('#grid').append('<div class="row" id="' + k + '"></div>')
for (var i = 0; i < Array[k][i]; i++)
{
var weight = Array[k][i];
var width = weight * 100 / totalCol;
$('#' + k).append('<div class="cell" style="width: ' + width + '%">column</div>');
console.log(weight);
}
}
HTML:
<div id="grid"></div>
Note that with your calculation 50 is a weight that is too much :)

Modify your JS to form a div based table and sample output should be as follows:
HTML
<div id="row1">
<div class="float-left div1">1st </div>
<div class="float-left div2">2st </div>
<div class="float-left div2">3st </div>
<div class="clear-fix"></div>
</div>
<div id="row2">
<div class="float-left div1">1st </div>
<div class="float-left div2">2st </div>
<div class="float-left div2">3st </div>
<div class="clear-fix"></div>
</div>
CSS
.float-left {
float:left;
border: 1px solid #ccc;
}
#row1 .div1 {
width:100px;
}
#row1 .div2 {
width:200px;
}
#row1 .div3 {
width:50px;
}
#row2 .div1 {
width:50px;
}
#row2 .div2 {
width:100px;
}
#row2 .div3 {
width:20px;
}
.clear-fix {
clear:both;
}

I think may be you can use this solution if you are comfortable. I created two tables and assigned a single row.
<table border='1' id="table0"></table>
<table border='1' id="table1"></table>
and script code is
var Array = [
[10, 5, 10],
[50, 2, 10]
];
for (var k = 0; k < Array.length; k++)
{
var totalCol = 0;
$.each(Array[k], function (){
totalCol += parseInt(this);
});
$('#table' + k).append('<tr id="' + k + '"></tr>')
for (var i = 0; i < Array[k].length; i++)
{
var weight = Array[k][i];
var width = weight * 100 / totalCol;
$('#' + k).append
('<td width="' + width + '%" >column</td>');
console.log(weight);
}
}
And fiddle link is here

Related

Javascript: Unexpected Token [ on line 92

I am having trouble with my html page here. On the console it shows me that there is 1 error on line 92 due to an unexpected token. Im trying to drag the image on the page to a designated box. Once dragged it should stay in the box. When I click on the image i should be able to drag it out of the box. I am not sure where i went wrong, but its completely not working at this point. All help is appreciated.
$(document).ready(function() {
var pictureIds = 20;
var Size = 400;
var table = $('#results').DataTable();
$.get("https://unsplash.it/list", function(Res) {
for (var i = 0; i < pictureIds; pictureIds++) {
var randomNumber = Math.floor(Math.random() * pictureIds.length)
$('.left').append($("<img>", {
src: "https://picsum.photos/" + Size + "/" + Size + "?image" + Res[randomNumber].id,
id: randomNumber,
class: "leftImg"
}));
}
(".leftImg").draggable({
revert: "invalid"
});
$("#right").droppable({
accept: ".leftImg",
drop: function(event, ui) {
ui.draggable.attr("id"),
$(ui.draggable).detach().css({
top: 2,
left: 0
}).appendTo($(this));
window.alert("Dropped image with an ID of " + ui.draggable.attr('id'));
//Create rows
var rowNode = table.row.add({
Res[image id].id,
Res[image id].filename,
Res[image id].author,
Res[image id].post_url
}).draw()
.node();
table.row.add({
Res[image id].id,
Res[image id].filename,
Res[image id].author,
Res[image id].post_url
}).draw();
$(rowNode).addClass(ui.draggable.attr('id'));
}
})
});
});
.left {
padding: 20px;
order: solid #000000 2px;
height: 50%;
width: 90%;
}
#right {
width: 30%;
border: solid #000000 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
float: right;
min-height: 400px;
}
<html>
<head>
<!-- head stuff goes here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
</head>
<body>
<!-- HTML content goes here -->
<div class="left">
<img class="leftImg" src="https://source.unsplash.com/random/200x200" id="102" />
<div id="right">
</div>
</div>
<table id="results" style="width:100%">
<thead>
<tr>
<th>id</th>
<th>filename</th>
<th>author</th>
<th>url</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</html>
I think you just got a little overzealous with some editing... A few typo's and I think you're good:
Missing the $ on the line " (".leftImg").draggable({"
The line var randomNumber = Math.floor(Math.random() * pictureIds.length) needs to have pictureIds.length changed to pictureIds as it is an int not an array.
Your loop is on the variable i but you incremented pictureId's instead of i.
The part where you are doing table.row.add had Res[image id] and I am not sure what is supposed to be in place if image id but Res[image id] is not valid. I commented that out in the code below but what I have edited below is draggable into the box.
$(document).ready(function() {
var pictureIds = 20;
var Size = 400;
var table = $('#results').DataTable();
$.get("https://unsplash.it/list", function(Res) {
for (var i = 0; i < pictureIds; i++) {
var randomNumber = Math.floor(Math.random() * pictureIds);
$('.left').append($("<img>", {
src: "https://picsum.photos/" + Size + "/" + Size + "?image" + Res[randomNumber].id,
id: randomNumber,
class: "leftImg"
}));
}
$(".leftImg").draggable({
revert: "invalid"
});
$("#right").droppable({
accept: ".leftImg",
drop: function(event, ui) {
ui.draggable.attr("id"),
$(ui.draggable).detach().css({
top: 2,
left: 0
}).appendTo($(this));
window.alert("Dropped image with an ID of " + ui.draggable.attr('id'));
//Create rows
/*
var rowNode = table.row.add({
Res[randomNumber].id,
Res[randomNumber].filename,
Res[randomNumber].author,
Res[randomNumber].post_url
}).draw()
.node();
table.row.add({
Res[randomNumber].id,
Res[randomNumber].filename,
Res[randomNumber].author,
Res[randomNumber].post_url
}).draw();
*/
$(rowNode).addClass(ui.draggable.attr('id'));
}
})
});
});

css not affecting div

I made this function to make 16 columns and rows.but I want the div that they are in to be on the right side, so for some reasons, I can't seem to change the div through (inline) css. I'm guessing its a problem with the function? Thanks for the help.
<html>
<body>
<div id="buttonContainer">
<button></button>
</div>
<div id="gridContainer" style = "left: 500px;">
</div>
</body>
<script>
const buttons = document.querySelector("#buttonContainer");
const btn1 = document.createElement("button");
btn1.classList.add("btn1");
buttonContainer.appendChild(btn1);
function divs(){
const gridContainer = document.querySelector("#gridContainer");
for(var i = 0; i < 17; i++){
var row = document.createElement("div");
row.className = "row";
for(var x = 1; x <= 17; x++){
var cell = document.createElement("div");
cell.className = "gridsquare";
cell.innerText = (i);
row.appendChild(cell);
}
gridContainer.appendChild(row);
}
}
divs();
</script>
</html>
There are different ways to move a div to the right. One is to give it a position:absolute (so it can move around freely) and then apply right : 0.
I have also removed the glitchy <button part.
const buttons = document.querySelector("#buttonContainer");
const btn1 = document.createElement("button");
btn1.classList.add("btn1");
buttonContainer.appendChild(btn1);
function divs() {
const gridContainer = document.querySelector("#gridContainer");
for (var i = 0; i < 17; i++) {
var row = document.createElement("div");
row.className = "row";
for (var x = 1; x <= 17; x++) {
var cell = document.createElement("div");
cell.className = "gridsquare";
cell.innerText = (i);
row.appendChild(cell);
}
gridContainer.appendChild(row);
}
}
divs();
#gridContainer{
position : absolute;
right: 0;
}
<div id="buttonContainer"></div>
<div id="gridContainer"></div>
EDIT : more modern/robust solution with Flexbox
The problem with position:absolute is that it kind of "detaches" the element from the rest of the DOM, so other elements start placing themselves underneath it, and it can quickly cause layout nightmares.
Here's an alternative with Flexbox :
.parent{
border : blue solid 2px;
height: 200px;
width: 100%;
display: flex;
justify-content: flex-end;
}
.child {
flex-basis : 150px; /* This is like width:150px */
background : green;
}
<div class="parent">
<div class="child"></div>
</div>

Dynamicaly fill table td based on array of elements

I need to fill the background of table td based on td values. Below is the sample code i wrote for filling the td cell value.
applySchedules = function(schedules){
$.map(schedules, function(value, index){
$('#'+value.start).css('background', 'green');
});
}
var temp = [{start:9, end:10}, {start:13, end:14}]
applySchedules(temp);
tr {
border-width:2px;
outline:solid;
}
td {
border-width:2px;
width:60px;
outline:solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<tr>
<td id="8">8AM</td>
<td id="9">9AM</td>
<td id="10">10AM</td>
<td id="11">11AM</td>
<td id="12">12PM</td>
<td id="13">1PM</td>
<td id="14">2PM</td>
<td id="15">3PM</td>
<td id="16">4PM</td>
<td id="17">5PM</td>
<td id="18">6PM</td>
<td id="19">7PM</td>
<td id="20">8PM</td>
</tr>
</table>
Basically i will get json array of time slots that are occupied for the given day. The problem comes when the slot span more than or less than 1hour. The time slots are allotted in multiple's 30 mins.
Like {start:10,end:11.30},{start:12,end:12.30},{start:14.30,end:15}
Looking for some pointers how to handle these kind of cases.
Sample Output :
I would advise:
increase number of spans such way, that there would be your 30 minute item
Don't use just numbered ID's -> it is not a very good way
$(function(){
var applySchedules = function(schedules){
$.map(schedules, function( value,index){
var startHour = value.start.split(":")[0];
var endHour = value.end.split(":")[0];
var halfStart = value.start.split(":")[1];
var halfEnd = value.end.split(":")[1];
var startContainer = $('#time'+ padLeft( startHour, 2));
var endContainer = $('#time'+ padLeft( endHour, 2));
if( parseInt( halfStart )){
startContainer.append( $("<div />").addClass("start") );
}
if( parseInt( halfEnd )){
endContainer.append( $("<div />").addClass("end") );
}
if( ( parseInt(endHour) - parseInt(startHour) ) > 0){
for( var i = 1; i < parseInt(endHour) - parseInt(startHour); i++ ){
$('#time'+ padLeft( (parseInt(startHour) + i)+"", 2)).append( $("<div />").addClass("full") );
}
}
});
}
function padLeft(str,size,padwith) {
if(size <= str.length) {
return str;
} else {
return Array(size-str.length+1).join(padwith||'0')+str
}
}
var initTime = function(){
for( var i =0; i< 24; i++ ){
var $item;
if( i < 12 ){
$item = $("<td/>").text( padLeft(i+"",2)+":00 AM" );
}else if( i == 12 ){
$item = $("<td/>").text( padLeft( (i)+"",2)+":00 PM" );
} else {
$item = $("<td/>").text( padLeft( (i-12)+"",2)+":00 PM" );
}
$item.attr("id", "time" + padLeft(i+"",2));
$("#timeContainer").append($item);
}
}
var temp=[{start:"9:00",end:"9:30"}, {start:"13:00",end:"13:30"}, { start:"14:00", end:"14:30"}, {start:"15:30", end:"18:30"}]
initTime();
applySchedules(temp);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<style>
tr{border-width:2px; outline:solid;}
td{border-width:2px; width:60px; outline:solid; position:relative;}
div.start {
width: 50%;
background: green;
position: absolute;
height: 100%;
top: 0;
right: 0;
z-index:-1;
}
div.end {
width: 50%;
background: green;
position: absolute;
height: 100%;
top: 0;
left: 0;
z-index:-1;
}
div.full{
width: 100%;
background: green;
position: absolute;
height: 100%;
top: 0;
z-index:-1;
}
</style>
<body>
<table>
<tr id="timeContainer">
</tr>
</table>
</body>
UPDATED ANSWER
Some first approach to code
If you are adamant on using your current setup, might I suggest using CSS gradients:
...
$('#'+value.start).css('background','repeating-linear-gradient(to right, #00FF33, #00FF33 23px, #FFFFFF 23px, #FFFFFF 46px)');
...
46px is the width of the <td> in the fiddle, this would probably have to be generated dynamically. The second two values are half of the width of the whole <td> which creates a gradient covering only half of the whole <td>. You can then split this into smaller section by doing more complicated maths but I suggest referring to https://css-tricks.com/stripes-css/ for more information on this trick.
Here's the fiddle:
http://jsfiddle.net/85mJN/190/

Complete function not forcing jquery to wait for end of animation

I am trying to use a counter in my complete function to make sure the animation of margin-top is completed before moving on. Right now, I have the counter in my MakeList(), and in my Spin() function, I console.log the counter and it doesn't recognize the counter++ because it fires before the animation finishes. Nobody I ask can figure out why.
** Note: I can't use timeOut's because the time is set to random (supposed to look like a slot machine ** Also, I can't find what this test platform is saying is an error, but the code runs on my machine. really the script-2.js is all i need to show to get point across though :)
// ********************************************************
// SLOT MACHINE ICONS. Each array has 3 icons for each slot
// ********************************************************
var array1 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array2 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array3 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
// Generates random # between 0 and 2. Used for choosing winner and creating random slots
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generates winning array item between coffee, tea and espresso
function win(whatArray){
var arrayItem = getRandomInt(0,2);
var winItem = whatArray[arrayItem];
return winItem;
}
// Populates each slot with random icons to spin through
var makeList = function(whatArray, whatSlot){
var slotArray = [];
for(i=0; i < 100; i++){
var randNum = getRandomInt(0,2); // Generate random number
var findItem = whatArray[randNum]; // Use random number to find associated array item
var slot = whatSlot; // Set which slot to append array item to (first, second or third)
$('#' + slot).append('<div>'+findItem+'</div>'); // Append icon to HTML
}
var winItem = win(whatArray); // Generate winning icon for slot
console.log("winner " + winItem);
$('#' + slot).append('<div>'+winItem+'</div>'); // Append winning icon to end of list
}
// Spin the slot and win some caffeine!
function Spin(){
window.counter = 0;
// Generate lists for each slot
makeList(array1, 'slot-1');
makeList(array2, 'slot-2');
makeList(array3, 'slot-3');
MoveSlots($('#slot1-wrapper'), 2500);
MoveSlots($('#slot2-wrapper'), 5200);
MoveSlots($('#slot3-wrapper'), 500);
//var running = true;
// console.log(running);
var slot1attr = $('#slot1-wrapper div').children().last().attr('data-id');
var slot2attr = $('#slot2-wrapper div').children().last().attr('data-id');
var slot3attr = $('#slot3-wrapper div').children().last().attr('data-id');
console.log('counter = ' + counter);
if(counter > 0){
if(slot1attr == slot2attr && slot1attr == slot3attr ){
console.log("WIN");
} else {
console.log("LOSE");
}
}
function MoveSlots(el, speed){
var time = speed;
time += Math.round(Math.random()*10000);
el.stop(true,true);
var marginTop = -(100 * 150 ); //change 100 to height placeholder
var running = true;
el.animate({
'margin-top':'+='+marginTop+'px'
}, {
'duration' : time,
'easing' : 'easeInOutQuint',
complete: function(){
console.log('yolo');
//$(this).on('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function(){
counter++;
console.log(counter);
//})
}
});
} // end MoveSlots
} // end Spin
body{
/*background-color:white;*/
padding:50px;
margin:50px;
background: #505f77 !important;
}
#slotWrapper {
width:410px;
height:150px;
margin:50px auto;
overflow: hidden;
position:relative;
border:1px solid #f00;
}
#slot1-wrapper, #slot2-wrapper, #slot3-wrapper {
margin-top:0;
position: relative;
}
.slot {
width:120px;
height:150px;
margin-right:25px;
text-align:center;
float:left;
position: absolute;
}
#slot-3 {
margin-right:0;
}
#slot-1 {
top:0;
left:0;
}
#slot-2 {
top:0;
left:145px;
}
#slot-3 {
top:0;
left:290px;
}
.slot div {
width:120px;
height:150px;
}
.slot div img {
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- <link rel="stylesheet" type="text/css" href="css/default.css" />
<link rel="stylesheet" type="text/css" href="css/component.css" /> -->
<div style="text-align:center">
<input type="button" value="spin!" onClick="Spin();" style="margin-top:4px;">
</div>
<div id="slotWrapper">
<div id="slot1-wrapper">
<div id="slot-1" class="slot"></div>
</div>
<div id="slot2-wrapper">
<div id="slot-2" class="slot"></div>
</div>
<div id="slot3-wrapper">
<div id="slot-3" class="slot"></div>
</div>
</div>
</body>
</html>
The problem is complete is executed asynchronously, ie the counter condition is executed is before the animations are completed.
You can use the animation promise to solve it
// ********************************************************
// SLOT MACHINE ICONS. Each array has 3 icons for each slot
// ********************************************************
var array1 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array2 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array3 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
// Generates random # between 0 and 2. Used for choosing winner and creating random slots
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generates winning array item between coffee, tea and espresso
function win(whatArray) {
var arrayItem = getRandomInt(0, 2);
var winItem = whatArray[arrayItem];
return winItem;
}
// Populates each slot with random icons to spin through
var makeList = function(whatArray, whatSlot) {
var slotArray = [];
for (i = 0; i < 100; i++) {
var randNum = getRandomInt(0, 2); // Generate random number
var findItem = whatArray[randNum]; // Use random number to find associated array item
var slot = whatSlot; // Set which slot to append array item to (first, second or third)
$('#' + slot).append('<div>' + findItem + '</div>'); // Append icon to HTML
}
var winItem = win(whatArray); // Generate winning icon for slot
console.log("winner " + winItem);
$('#' + slot).append('<div>' + winItem + '</div>'); // Append winning icon to end of list
}
// Spin the slot and win some caffeine!
function Spin() {
var counter = 0;
// Generate lists for each slot
makeList(array1, 'slot-1');
makeList(array2, 'slot-2');
makeList(array3, 'slot-3');
var p1 = MoveSlots($('#slot1-wrapper'), 2500);
var p2 = MoveSlots($('#slot2-wrapper'), 5200);
var p3 = MoveSlots($('#slot3-wrapper'), 500);
$.when(p1, p2, p3).then(function() {
//var running = true;
// console.log(running);
var slot1attr = $('#slot1-wrapper div').children().last().attr('data-id');
var slot2attr = $('#slot2-wrapper div').children().last().attr('data-id');
var slot3attr = $('#slot3-wrapper div').children().last().attr('data-id');
console.log('counter = ' + counter);
if (counter > 0) {
if (slot1attr == slot2attr && slot1attr == slot3attr) {
console.log("WIN");
} else {
console.log("LOSE");
}
}
});
function MoveSlots(el, speed) {
var time = speed;
time += Math.round(Math.random() * 10000);
el.stop(true, true);
var marginTop = -(100 * 150); //change 100 to height placeholder
var running = true;
el.animate({
'margin-top': '+=' + marginTop + 'px'
}, {
'duration': time,
'easing': 'easeInOutQuint',
complete: function() {
console.log('yolo');
counter++;
console.log(counter);
}
});
return el.promise();
} // end MoveSlots
} // end Spin
body {
/*background-color:white;*/
padding: 50px;
margin: 50px;
background: #505f77 !important;
}
#slotWrapper {
width: 410px;
height: 150px;
margin: 50px auto;
overflow: hidden;
position: relative;
border: 1px solid #f00;
}
#slot1-wrapper,
#slot2-wrapper,
#slot3-wrapper {
margin-top: 0;
position: relative;
}
.slot {
width: 120px;
height: 150px;
margin-right: 25px;
text-align: center;
float: left;
position: absolute;
}
#slot-3 {
margin-right: 0;
}
#slot-1 {
top: 0;
left: 0;
}
#slot-2 {
top: 0;
left: 145px;
}
#slot-3 {
top: 0;
left: 290px;
}
.slot div {
width: 120px;
height: 150px;
}
.slot div img {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" rel="stylesheet" />
<div style="text-align:center">
<input type="button" value="spin!" onClick="Spin();" style="margin-top:4px;">
</div>
<div id="slotWrapper">
<div id="slot1-wrapper">
<div id="slot-1" class="slot"></div>
</div>
<div id="slot2-wrapper">
<div id="slot-2" class="slot"></div>
</div>
<div id="slot3-wrapper">
<div id="slot-3" class="slot"></div>
</div>
</div>

How to create pair game using node values and set a setTimeout() method

I want to create a pair game that if the same textnode is matched it will set the background in white to reveal the matched textnode if not it will set a timeout and get back in original state.
The Problem of this is if I use the childNodes.nodeValue in match it saids that ChildNodes.nodeValue is not a function. And I try another code. I declare a variable that calls the element tag name of div which is I append a textNode in div. I want to compare two consecutive childNodes of div and if it is the same node, I change the color of the background to white. and I use the setTimout method, if not the color of background will go back again in original state which is black, I am pretty confused about this.
can you scan my code and help me to figure out what is the problem of this code?
here is the code.
<html>
<head>
<style>
div.row {
clear : left;
margin: auto;
width: 520px;
}
div.col {width:100px;
height:100px;
border: 3px solid black;
float : left;
margin: 10px;
font-size: 75px;
text-align: center;
background-color: black;
}
</style>
</head>
<body>
<div class="row">
<div id="00" class="col"></div>
<div id="01"class="col"></div>
<div id="02"class="col"></div>
<div id="03"class="col"></div>
</div>
<div class="row">
<div id="10" class="col"></div>
<div id="11"class="col"></div>
<div id="12"class="col"></div>
<div id="13"class="col"></div>
</div>
<div class="row">
<div id="20" class="col"></div>
<div id="21"class="col"></div>
<div id="22"class="col"></div>
<div id="23"class="col"></div>
</div>
<div class="row">
<div id="30" class="col"></div>
<div id="31"class="col"></div>
<div id="32"class="col"></div>
<div id="33"class="col"></div>
</div>
<script>
var size = 4;
var player = 0;
var board = new Array(size);
for (var i = 0; i < size; i++) {
board[i] = new Array(size);
for (var j = 0; j < size; j++) {
board[i][j] = 0;
}
}
var div_elements = document.getElementsByClassName("col");
for (var i = 0; i < div_elements.length;i++) {
div_elements[i].addEventListener("click", function() {mclick(this);});
}
var count=0;
function mclick(obj) {
if(match(div_elements.childNodes[0].nodeValue) == match(div_elements.childNodes[1].nodeValue)
{
obj.style.backgroundColor="white";
}
else{
setTimeout(function(){ obj.style.backgroundColor="white" }, 1000);
}
}
function shuffle() {
var value;
var text;
var text_node;
for (var i = 0; i < (size * size) ; i++) {
value = Math.ceil(Math.random() * 8);
board[Math.floor(i/4)][i %4] = value;
}
for (var i = 0; i < div_elements.length; i++)
{
text = board[Math.floor(i/4)][i%4];
text_node = document.createTextNode( text);
div_elements[i].appendChild(text_node);
}
}
shuffle();
</script>
</body>
</html>
You must be more specific. What kind of problem are you having? What are the error messages? What do you do that triggers the problem?
At least, put the code in a pastebin.com or something similar so that others don't need to setup a project for testing your whole stuff.

Categories