Create table with Javascript - javascript

I'm creating some kind of "Mario puzzle" all in one file for now.
I managed to create a table using window prompt. I don't know how to make height and width fixed so it will be the same size as the pictures on the top.
Later on, I will make an option to select a picture and insert it in the blank square. Any advice please?
After the user inputs rows and columns:
Playing around and making something, you get the point
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mario</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
table,td {
border: 1px solid grey;
border-collapse: collapse;
margin: 10px;
background-color: silver;
}
img {
display: block;
}
</style>
</head>
<body>
<table>
<tr>
<td><img src="images/sprite1.gif" alt="sprite1.gif"></td>
<td><img src="images/sprite2.gif" alt="sprite2.gif"></td>
<td><img src="images/sprite3.gif" alt="sprite3.gif"></td>
<td><img src="images/sprite4.gif" alt="sprite4.gif"></td>
<td><img src="images/sprite5.gif" alt="sprite5.gif"></td>
<td><img src="images/sprite6.gif" alt="sprite6.gif"></td>
<td><img src="images/sprite7.gif" alt="sprite7.gif"></td>
<td><img src="images/sprite8.gif" alt="sprite8.gif"></td>
<td><img src="images/sprite9.gif" alt="sprite9.gif"></td>
<td><img src="images/sprite10.gif" alt="sprite10.gif"></td>
<td><img src="images/sprite11.gif" alt="sprite11.gif"></td>
<td><img src="images/sprite12.gif" alt="sprite12.gif"></td>
<td><img src="images/sprite13.gif" alt="sprite13.gif"></td>
<td><img src="images/sprite14.gif" alt="sprite14.gif"></td>
<td><img src="images/sprite15.gif" alt="sprite15.gif"></td>
<td><img src="images/sprite16.gif" alt="sprite16.gif"></td>
</tr>
</table>
<script type="text/javascript">
var r = window.prompt("Please enter rows:"); //vrstica tr
while(r<5 || r>20){
r = window.prompt("Wrong, enter a number between 5 and 20:");
}
var c = window.prompt("Please enter columns:"); //stoplec td
while(c<10 || c>40){
c = window.prompt("Wrong, enter a number between 10 and 40:");
}
document.write('<table>');
for(i=1;i<=r;i++) {
document.write("<tr>");
for(j=1;j<=c;j++) {
document.write("<td>"+" "+"</td>");
}
document.write("</tr>");
}
document.write('</table>');
</script>
</body>
</html>

As mentioned, do not use document.write. Create the elements in memory and then append to the DOM when ready.
As for height and width; 1) set the inline style of the tds or 2) apply height and width CSS.
Make sure that wherever you set the dimensions, to make it the same as the images above. Option #2 is the preferred approach.
Option #1
function el( tagName ) {
return document.createElement( tagName );
}
var rows = 5;
var cols = 10;
var table = el( 'table' );
for ( var i = 0; i < rows; i++ ) {
var tr = el( 'tr' );
for ( var j = 0; j < cols; j++ ) {
var td = el( 'td' );
td.style.width = '20px';
td.style.height = '20px';
tr.appendChild( td );
}
table.appendChild( tr );
}
document.body.appendChild( table );
td {
border: 1px solid #ccc;
}
Option #2
function el( tagName ) {
return document.createElement( tagName );
}
var rows = 5;
var cols = 10;
var table = el( 'table' );
for ( var i = 0; i < rows; i++ ) {
var tr = el( 'tr' );
for ( var j = 0; j < cols; j++ ) {
tr.appendChild( el( 'td' ) );
}
table.appendChild( tr );
}
document.body.appendChild( table );
td {
border: 1px solid #ccc;
width: 20px;
height: 20px;
}

Related

Random Color for <tr>

So overall I am trying to make the boxes change color when someone puts a mouse over them. Color has to be random. I know I am missing a connection point between my functions but I cant figure out what it is.
<!DOCTYPE html>
<html onmousedown='event.preventDefault();'
onmouseenter = "colorize();"
>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
Create a function called colorize that is passed an element object as its
parameter and sets the elements background color style property using the
rgb(r,g,b) method setting each r,g and b to a random number between 0 and
255.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function colorize(co) {
document.body.style.background = co;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
Use document.write() and for-loops to fill in the table to create a 16x16 box table. For each td element, create a onmouseenter call to colorize, passing it the element itself (this).
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>
I'm not sure what you wanted to do with body background, nothing said about that in your text. ALos your colorizer func is overwritten. maybe you wanted something like this... ?
<!DOCTYPE html>
<html>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
function colorize(el) {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
el.style.backgroundColor = '#' +r+g+b;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td onMouseEnter='colorize(this);'></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>
You need to have your colorize function update each cell in your table. Replace both colorize() and colorize(co) with one function:
function colorize() {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
for (var i = 0; i < document.getElementsByTagName("td").length; i++){
document.getElementsByTagName("td")[i].style.backgroundColor = "#"+r+g+b;
}
}
i play with Ids and adding onmousedown in html tag that calls the func.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function change(){
var x = document.getElementById("1");
var y = document.getElementById("2");
x.style.color = colorize();
y.style.color = colorize();
}
<table frame="box" onmousedown="change()"id="1" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
<table frame="box" onmousedown="change()" id="2" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>February</td>
<td>$200</td>
</tr>
</table>

Javascript table is not rendering using CSS

I created a table using JavaScript, but it doesn't render using my css. so how can I make it work? actually i need more help, my idea is to create a screen that has one button and once you click on it a menu which is a table of one column starting at the top of the screen and end at the end of the screen should be showing. the table would be scrollable and each row has text (url text) with no url line under the text, so when you click on it the page open in all of the screen behind the table and the button. the button should be always showing (but it disappears when i click on it).
the main.js file is
function makeTableHTML() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
var myArray = [ [ "Name, http://www.google.com" ],
[ "Name, http://www.google.com" ] ];
var result = '<table width = "300">';
for (var i = 0; i < myArray.length; i++) {
result += "<tr><td>";
if (i < 10) {
result += "0" + i + " ";
} else {
result += i + " ";
}
result += '<a href="' + myArray[i][0] + '">';
result += myArray[i][1] + "</a>";
result += "<td></tr>";
}
result += "</table>";
document.write(result);
document.getElementById("channelsmenu").classList.toggle(result);
}
function hideTableHTML() {
var x = document.getElementById('channelsmenu');
x.style.display = 'none';
}
and my html is
<!DOCTYPE html>
<html>
<head>
<title>5Star-IPTV</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/main.js"></script>
</head>
<body>
<div>
<table>
<tr>
<td>
<div id="channelsmenu" class="dropdown-content"></div>
</td>
<td class="buttons-col"><input type="image"
src="channels-menu.png" class="buttons" alt="channels menue"
onMouseOver="this.src='channels-menu-1.png'"
onMouseOut="this.src='channels-menu.png'" onclick="makeTableHTML()" /></td>
<td class="buttons-col"><input type="image"
src="return-button.png" alt="return button" class="buttons"
onMouseOver="this.src='return-button-1.png'"
onMouseOut="this.src='return-button.png'" onclick="hideTableHTML()" /></td>
</tr>
</table>
</div>
</body>
</html>
and this is the css
table {
width: 100%;
border: 1px solid black;
background-color: #808080;
}
tr {
width: 100%;
align: right;
}
th, td {
text-align: right;
} background-color: #808080;
}
.buttons-col {
text-align: center;
width: 90px;
padding-top: 5px;
}
in HTML you open "th" and close it as "tr". Secondly, please learn to write/format your code properly - it'll be easier to read your code and to help you.
Besides, use the < script > tag at the end of the HTML or run your JS in the function on event DOMContentLoaded

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/

two td tag don't slide side by side

Hello I develop a app where td appear and disapear side by side.
lastInsertTd = 0;
function newSlidingTd() {
tr = jQuery('#myline');
var lastTd = jQuery('#myline').children().last();
td = jQuery("<td></td>")
.attr('id', 'slidingTd' + lastInsertTd+1)
.attr('style', 'display:none;vertical-align:top;width:100%');
tr.append(td);
tdSuivant = jQuery('#slidingTd' + lastInsertTd+1);
tdActuel = jQuery('#slidingTd' + lastInsertTd);
/*animation*/
tdActuel.toggle('slide', {
direction: 'left'
}, 500);
tdSuivant.toggle('slide', {
direction: 'right'
}, 500);
lastInsertTd = lastInsertTd+1;
}
table {
width:100px
}
td {
border: black solid 1px;
width:100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<table>
<tr id="myline">
<td id='slidingTd0' onclick="newSlidingTd()">
1
</td>
</tr>
</table>
But when I call my event, my new td doesn't slide from the right but a little bit lower. How can I go through this "bug"? (this also happen when I create div inside td)
if it's slightly lower, then most likely it's some issue with displaying whitespaces.
Try setting line-height: 0; in the parent element (tr I'd guess), or remove the whitespace between < /td >< td >

Allowing different widths of columns in rows

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

Categories