Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have Create button on the body, when i will click on that button, i need to create 10 divs dynamically, and give random color and position. Like this

What I have tried:

I have tried like this, but after click on Create button, it creates that 10 divs on each other, so i see only 1 div. What's wrong in my code? i need sort that divs in different position, not on each other.

$(document).ready(function(){
    $("#btn").click(function(){
    var r = parseInt(Math.random()*256);
    var g = parseInt(Math.random()*256);
    var b = parseInt(Math.random()*256);
    var color = `rgb(${r},${g},${b})`;
    var ww = $(window).width();
    var wh = $(window).height();
    var posx = (Math.random() * ww);
    var posy = (Math.random() * wh);
    var div=("<div></div>");
    for(var i = 0; i <= 10; i++){
      $(div).css({"background": color, "width":"50", "height":"50","position":"absolute", "top": posy, "left": posx}).appendTo("body");
    }
    })
});
Posted
Updated 3-Aug-18 9:31am

You want to create 10 <div>s with random positions and colours.

But you declare the positions and colours outside of your loop. The values don't change within the loop, so you create all 10 elements at the same position, and with the same colour.

Move the position and colour calculations inside the loop.
JavaScript
// These variables don't change within the loop:
var ww = $(window).width();
var wh = $(window).height();
var div = "<div />";

for (var i = 0; i <= 10; i++){
    // These variables need to be different for each iteration:
    var r = parseInt(Math.random()*256);
    var g = parseInt(Math.random()*256);
    var b = parseInt(Math.random()*256);
    var color = `rgb(${r},${g},${b})`;
    var posx = (Math.random() * ww);
    var posy = (Math.random() * wh);
    
    $(div).css({"background": color, "width":"50", "height":"50","position":"absolute", "top": posy, "left": posx}).appendTo("body");
}
 
Share this answer
 
you can use position:
relative
in css
 
Share this answer
 
v2
Comments
Suren97 1-Aug-18 6:17am    
so what can i do??
Suren97 1-Aug-18 6:28am    
I have tried to use position relative but that time it is positioned under one another, like this http://prntscr.com/kdawia
Member 11621026 2-Aug-18 0:44am    
what acute requirement you want can you elaborate which position you want a div.
is row wise ya column wise

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900