user6654733 user6654733 - 1 year ago 85
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 ,

<meta charset="utf-8" />
border:solid 1px;
width: 60%;
height: 400px;
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
.row:after {
display: table ;
.col-1{ width: 15%;
padding: 2px;}

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

and i want output something looks like as,


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download