user6654733 user6654733 - 4 months ago 29
CSS Question

Create dynamic Rectangle collection in html using js

Hello All iam a begineer in html and js ,and iam trying to create webPage containing rectangle collection in which when a new rectangle is created is placed beside the previous rectangle,
i have created a div element and trying to add newly created div(rectangle shape with background color different based on condition),but iam not able to get the desired result,
please help me,
i wrote the following code ,

<html>
<head>
<title>parkIn</title>
<meta charset="utf-8" />
</head>
<style>
.ParkSlots{
border:solid 1px;
width: 60%;
height: 400px;
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
display:inline;
}
.row:before,
.row:after {
content:"";
display: table ;
clear:both;
}
.col-1{ width: 15%;
margin-left:10px;
height:350px;
padding: 2px;}
</style>

<body onload="viewCreate()">
<div class="ParkSlots">
<div class="row" id="content">
</div>
</div>
</body>
<script language="javascript">
function viewCreate(){
for(int i=0;i<5;i++)
{
if(i%2 == 0)
{
createGreenBox();
}
else{
createRedBox();
}
}
}
function createRedBox()
{
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'red';
document.getElementById('content').appendChild(div);
}
function createGreenBox()
{
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'lightgreen';
document.getElementById('content').appendChild(div);
}
</script>
</html>


and i want output something looks like as,

image

Please help me,iam sorry if i have done mistake,i dont know how silly mistake i have done ,please help me

Answer

Just in glancing at your code, I see at least two typos:

  • for (int i = 0; i < 5; i++) { - in JS, int is not used in this way. Use var i = 0...
  • var = document.createElement('div'); - you're missing a variable name on this line in both create box functions. I assume, from the rest of the code you need var div = document.createElement('div');

The rest will be CSS. In your stylesheet you're applying the border to the outter most containing div, from you're example, you need to apply that to the .col-1 class. You'll also want to use display:inline-block on that class, and set widths and margins to play nicely with the border size. I took the liberty of creating a jsfiddle for you with my recommended changes.

Comments