Code:
<html>
<head>
<title>A</title>
<style type="text/css">
.rect {
background-color: white;
border: 1px solid gray;
color: gray;
}
</style>
<script type="text/javascript">
function Rectangle(l, w, x, y) {
this.length = l;
this.width = w;
this.area = l * w;
this.x = x || Math.floor(Math.random() * 640);
this.y = y || Math.floor(Math.random() * 480);
this.dragging = false;
this.id = Rectangle.currentID++;
}
Rectangle.prototype.move = function(x, y) {
this.x = x;
this.y = y;
};
Rectangle.prototype.draw = function() {
var first = !this.element;
if(first) {
this.colour = (function() {
var light = [];
for(var i=0;i<3;i++)
light.push(Math.floor(Math.random() * 256).toString(16));
return "#" + light.join("");
})();
this.element = document.createElement("div");
this.element.rect = this;
this.element.style.backgroundColor = this.colour;
this.paragraph = document.createElement("p");
this.paragraph.style.top = "47%";
this.paragraph.style.position = "relative";
this.paragraph.style.textAlign = "center";
this.element.appendChild(this.paragraph);
this.info = document.createTextNode("");
this.paragraph.appendChild(this.info);
this.paragraph.appendChild(document.createElement("sup")).appendChild(document.createTextNode("2"));
this.element.onclick = function() {
this.rect.remove();
};
}
this.info.nodeValue = this.length + "cm x " + this.width + "cm = " + this.area + "cm";
this.element.style.position = "absolute";
this.element.style.width = this.width + "cm";
this.element.style.height = this.length + "cm";
this.element.style.top = this.y + "px";
this.element.style.left = this.x + "px";
this.element.className = "rect";
this.element.id = "rect" + this.id;
if(first) document.body.appendChild(this.element);
};
Rectangle.prototype.remove = function() {
this.paragraph.removeChild(this.info);
delete this.info;
this.element.removeChild(this.paragraph);
delete this.paragraph;
document.body.removeChild(this.element);
delete this.element;
delete this;
}
Rectangle.prototype.resize = function(l, w) {
this.length = l;
this.width = w;
this.area = l * w;
};
Rectangle.currentID = 0;
Rectangle.allRectangles = [];
Rectangle.create = function() {
var l = "", w = "";
while(isNaN(parseFloat(l))) {
if(l) window.alert(l + " is not a valid length.");
l = window.prompt("Please enter the length of rectangle in centimeters:");
}
while(isNaN(parseFloat(w))) {
if(w) window.alert(w + " is not a valid width.");
w = window.prompt("Please enter the width of rectangle in centimeters:");
}
var r = new Rectangle(l, w);
rects.push(r);
r.draw();
return r;
};
var rects = [];
</script>
</head>
<body>
<input type="button" onclick="Rectangle.create();" value="Create Rectangle">
</body>
</html>
Bookmarks