JSFiddle - React, Tailwind, and code Playground
by Chace
HTML
<div id="myRoot"></div>
CSS
div#myRoot {
border: 1px solid gray;
padding: 7px;
margin: 0px;
font-size: 1em;
background: #fff;
}
div.planet {
border: 1px solid gray;
padding: 3px;
margin: 3px;
border-radius: 7px;
background: #fff;
font-family: tahoma;
font-size: 0.8em;
}
button {
background-color: #000;
border: none;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 0.8em;
border-radius: 5px;
padding: 3px 3px;
margin: 3px;
}
button:hover {
background-color: #999999;
}
JavaScript
class Planet {
constructor(name, radius) {
this.name = name;
this.radius = radius;
}
getSurfaceArea() {
var surfaceArea = 4 * Math.PI * Math.pow(this.radius, 2);
//console.log(surfaceArea + " square km!");
return surfaceArea;
}
set radius(value) {
//console.log("Setting value!");
this._radius = value;
}
get radius() {
//console.log("Getting value!");
return this._radius;
}
}
Number.prototype.formatNum = function(n, x) {
var re = '(\\d)(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$1,');
};
function changeSA(id, name, radius) {
console.log("ID: " + id);
console.log("Name: " + name);
console.log("Radius: " + radius);
}
var listOfPlanets = [
{
Name: "Venus",
Radius: "637"
}, {
Name: "Earth",
Radius: "6378"
}, {
Name: "Congo",
Radius: "2354"
}, {
Name: "Wazinga!",
Radius: "9901"
}];
var myRoot = document.getElementById('myRoot');
for (let x = 0; x < listOfPlanets.length; x++) {
var iDiv = document.createElement("div");
var iButton = document.createElement("button");
var anObjectName = "iPlanet" + x;
var iPlanet = new Planet(listOfPlanets[x].Name, listOfPlanets[x].Radius);
iDiv.id = "planet" + x;
iDiv.className = "planet";
iDiv.innerHTML = "<b>" + iPlanet.name + "</b> (" + x + ")<br/>";
iDiv.innerHTML += "Radius: " + iPlanet.radius + " km<br/>";
iDiv.innerHTML += "Surface Area: " + iPlanet.getSurfaceArea().formatNum(2) + " square km" + "<br/>";
iButton.innerHTML = "Change Radius";
iButton.addEventListener ("click", function() {
changeSA("planet" + x, listOfPlanets[x].Name, listOfPlanets[x].Radius);
});
iDiv.appendChild(iButton);
myRoot.appendChild(iDiv);
console.log(iPlanet.radius);
}