JSFiddle - React, Tailwind, and code Playground

by Ramya Ranganathan

HTML

<form id="objectForm" name="objectForm" method="GET" action="#">
      <p>
        <label for="squareSizeId">Square Size (in px):</label>
        <input type="text" id="squareSizeId" name="squareSize" value="" />
      </p>
      <p>
        <label for="squareColorId">Square Color:</label>
        <input type="text" id="squareColorId" name="squareColor" value="" />
      </p>
      <input type="button" id="submitButton" name="submitBut" value="Add Square!">
    </form>

    <div id="squareCanvas">
    </div>

JavaScript

// Create an array to hold all of the square objects
var squares = [];

// Create the Square "class"
function Square(size, color) {
	this.size  = size;
	this.color = color;	
}

function writeToPage (aSquare) {
		var myCanvas = document.getElementById("squareCanvas");

		console.log(aSquare);

		// Create new paragraph node
		var paragraph = document.createElement("p");

		// Set the style of the paragraph
		paragraph.style.height = aSquare.size + "px";
		paragraph.style.width  = aSquare.size + "px";
		paragraph.style.backgroundColor = aSquare.color;

		// Add paragraph to the "Canvas"
		myCanvas.appendChild(paragraph);
}

function submitSquare() {
	// Get values
	var size = document.getElementById("squareSizeId").value;
	var color = document.getElementById("squareColorId").value;
	console.log("Size: " + size + "; Color: " + color);

    // Write the square object to the page
	var mySquare = new Square(size, color);
	writeToPage(mySquare);

	// Add square object to an array of square objects
	squares.push(mySquare);
	console.log(squares);

	// Write the array to local storage
	var jsonString = JSON.stringify(squares);
	console.log(jsonString);

	localStorage.setItem("squareStorage", jsonString);

}