# Algorithm for subdividing html-elements

I am trying to write a module that automatically subdivides div-elements, given some initial parameters.

I've prepared the following jsfiddle.

What I am doing at the moment is:

1. Setting the width and height of the parent element.
2. Setting the child elements to float left and assigning percentual width and height to them, based on the specified parameters.

that.createDivisionData = function(paramObj) {

var
numOfDivisions = paramObj.divisions,
widthTop = paramObj.widthTop,
heightTop = paramObj.heightTop,
widthBottom = paramObj.widthBottom,
widthBlock = paramObj.blockWidth,
heightBlock = paramObj.blockHeight,
data = [];

for ( var i = 1; i <= numOfDivisions; i++) {
var divisionObj = {};
if (i < 3) {
divisionObj.widthPerc = i % 2 ? widthTop + '%' : (100 - widthTop) + '%';
divisionObj.width = i % 2 ? widthTop * widthBlock / 100 : (100 - widthTop) * widthBlock / 100;
divisionObj.heightPerc = heightTop + '%';
divisionObj.height = heightBlock * heightTop / 100;
} else {
divisionObj.widthPerc =  i % 2 ? widthBottom + '%' : (100 - widthBottom) + '%';
divisionObj.width =  i % 2 ? widthBottom * widthBlock / 100 : (100 - widthBottom) * widthBlock / 100;
divisionObj.heightPerc = (100 - heightTop) + '%';
divisionObj.height = (100 - heightTop) * heightBlock / 100;
}
data.push(divisionObj);
}
return data;
};


The way I am doing it at the moment actually works. But it feels somehow wrong, dirty, unfinished, you name it. I know this is a subjective question, but maybe someone has an idea. How can I do this in a cleaner way?

• if (i < 3) { ... What is different about those first two items versus the rest? Jun 1 '15 at 21:16
• The first two items will have the heightTop value assigned as their height, whereas the following items will get the inverted heightTop value. Jun 1 '15 at 21:22

A lot of what you are doing is repeated code so you should DRY it out. For instance, widthPerc is the same code except for the values of widthTop and widthBottom. We can also simply all of our checks by setting them up as vars. So that could be re-written like this:

var isFirstTwo = !!( i < 3 ); // go ahead and just eval once
var isEven = !!( i % 2 ); // go ahead and just evalonce

//which width value do we want?
var widthDir = ( isFirstTwo ) ? widthTop : widthBottom;
//is it an even number?
widthDir = ( isEven ) ? widthDir : 100 - widthDir;
widthBlock = widthDir * widthBlock / 100;

divisionObj.widthPerc = widthDir +'%';
divisionObj.width = widthBlock;


This reduces a lot of your code. You could follow a similar technique for height (it's actually easier than width).

var heightTop = ( isEven ) ? heightTop : (100 - heightTop);
var heightBlock =  heightBlock * heightTop / 100
divisionObj.heightPerc = heightTop + '%';
divisionObj.height = heightBlock;


Hope that helps. I have updated the fiddle. Let me know if you have questions or comments.

• I am leaving for the day but I will check back tomorrow morning. Jun 1 '15 at 21:59