HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Father-son project: Drawing on a grid

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gridfathersonprojectdrawing

Problem

I made this bit of code that uses jQuery in a simple HTML file to see if my son would think it is fun/interesting and to help me with my jQuery skills. The thing that was hard was the selectors towards the bottom of the script block. I am wondering if there is a better way to do this. Warning: it auto-refreshes to 're-pixel' the screen (for lack of a better word).

Also I am building tables but I am sure they are not right, it was my intention to grab the innerwidth and innerheight and create a table that is divided into fractional squares that perfectly fill the view-able browser screen. I had trouble getting the logic right.

Also, I had to place a span tag in side the ` blocks so the wouldn't collapse on me. I wanted to do this in divs but I wasn't sure how to get the same effect.



$(document).ready(function () {
// find random colors
function colorMe() {
var newColor = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6);
return newColor;
}
// not sure about this but i got it to work in some wierd way.
var wb = Math.floor(window.innerWidth / 200);
var hb = Math.floor(window.innerHeight / 200);

// table buildout append cells and rows to the table.
// Note the yucky span tag to prevent td collapse
var table = $('');
for (i = 0; i ');
for (j = 0; j ').html('');
table.append(row);
row.append(row1);
}
}
// table to body append
$('body').append(table);

// mouse event to emulate a pen commenting out the last two give it a fun calligraphy look
$("td").hover(function () {
var whoIsMe = $(this).index();

$(this).stop()
.animate({
"opacity": "0"
}, "fast");

$(this).next("td")
.stop()
.animate({
"opacity": "0"
}, "fast");

$(this).prev("td")
.stop()
.animate({
"opacity": "0"
}, "fast");

$(this).parent()
.next()
.children("td")
.eq(whoIsMe)
.stop()
.animate({
"op

Solution

To make them square:

var size = Math.max(window.innerWidth,window.innerHeight)/200;
var xbound = Math.floor(window.innerWidth/size);
var ybound = Math.floor(window.innerHeight/size);


Simply use xbound and ybound as the upper limits in the for loops.

Try to use CSS where you can.

Additionally, your script loads very slowly because of the excessive DOM manipulation. Rather than adding each element to the page one by one, create a single object and then paste that in one go. Just add up the html code with the += operator before inserting it into the page.

Code Snippets

var size = Math.max(window.innerWidth,window.innerHeight)/200;
var xbound = Math.floor(window.innerWidth/size);
var ybound = Math.floor(window.innerHeight/size);

Context

StackExchange Code Review Q#45518, answer score: 3

Revisions (0)

No revisions yet.