<form id="myform" style="padding:20; font-family: 'Courier New', Courier, monospace;" onsubmit="addField(event.currentTarget.x.value, event.currentTarget.y.value); return false;">
<fieldset>
<legend>Add a field of chosen size</legend>
<div style="background-color: lightgrey; padding: 10px;">
<label for="x">x:</label>
<input type="text" id="x" name="x" value="520"><br><br>
<label for="y">y:</label>
<input type="text" id="y" name="y" value="325"><br><br>
<input type="submit" value="Set field size">
</div>
</fieldset>
</form>
<form style="text-align: center;" id="button" onsubmit="return false"></form>
<p style="font-size: 22px; font-family: Arial, Helvetica, sans-serif; margin-left:25px">Base Case: <span id="basecase"></span></p>
<div id="fieldContainer" style="overflow:scroll; margin-bottom:100px; margin-right:20px;"></div>
</div>
function sideInfo(x, y) {
return x > y
? { largestSide: x, smallestSide: y }
: { largestSide: y, smallestSide: x };
}
function findBaseCase(x, y) {
const { smallestSide, largestSide } = sideInfo(x, y);
const remainder = largestSide % smallestSide;
return remainder === 0 ? smallestSide : findBaseCase(remainder, smallestSide);
}
function selectBgColor(index) {
if (index % 2 === 0) return "green";
return "lightgreen";
}
function splitField(x, y) {
document.getElementById("field").innerHTML = null;
const { largestSide, smallestSide } = sideInfo(x, y);
const base = findBaseCase(x, y);
if (base < 3) {
alert(
`The calculation provides a square that's too small - your base case is ${base}.`
);
return;
}
const amountOfSquares = (largestSide / base) * (smallestSide / base);
document.getElementById("basecase").innerHTML = base;
for (let i = 0; i < amountOfSquares; i++) {
const div = document.createElement("div");
div.setAttribute(
"style",
`float:left; width:${base}px; height:${base}px; background-color:${selectBgColor(
i
)}; outline-style:solid; outline-color:#fff`
);
document.getElementById("field").append(div);
}
}
function addField(x, y) {
document.getElementById("fieldContainer").innerHTML = null;
var div = document.createElement("div");
div.setAttribute("id", "field");
div.setAttribute(
"style",
`width:${x}px; height:${y}px; outline-style:dotted; margin:10px;`
);
document.getElementById("fieldContainer").append(div);
splitField(x, y);
}
window.onload = function () {
document.forms["myform"].dispatchEvent(new Event("submit"));
};
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.