I am trying to create a grid of squares that could fit in any dimensions container (ie. the squares resize themselves or add/delete new ones if the container width/height are changed).
I am going the Javascript route for now (and Jquery, for now) - there might be a flexgrid solution but since I plan to populate my squares with some kind of cellular automata type thingie, I figured that it wouldn't hurt. This doesn't solve my problem, since the number of lines of squares seems to be fixed.
Here is what I have so far:
var screen = {
width: 0, // these I get with jquery, on load and on resize events
height: 0
}
var values = {
min: 100, // minimum square size
max: 500 // maximum square size
}
var findSize = function() {
var r = 1;
var currVal = values.min;
while (r > 0) {
if((screen.width % currVal) === (screen.height % currVal)) {
// this should mean that they are both divisible by this value, right?
// get out of the loop and return value
r = 0;
return currVal;
} else if (currVal > values.max ) {
// if we exceed the maximum size, get out of the loop and return 0
r = 0;
return 0;
} else {
// if not, increment a bit
currVal += 0.25; // increment the value to check the modulo against
}
}
}
Calling the findSize()
function should return either the dimensions of the square (from which I can then build my grid easily, with either floated squares or absolutely positioned ones.
The problem is that it doesn't. Well it sometimes does. And it also pretty often gives me nothing...
The border are done with box-shadow
so it shouldn't affect the dimensions.
So I am wondering...
- Where is my code faulty?
- Can I change my function so it return always something (maybe with smaller incrementations?). I can work with rounded values for display purpose.
- The brute force aspect doesn't seem too efficient. Is there a way to refactor this so the loop is shorter?
Thanks a lot!