Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Concentric Circles with JavaScript/jQuery

I am trying to generate 10 concentric circles from one object with jQuery using a for loop.

I've written this in my jsfiddle http://jsfiddle.net/JoshuaWaheed/NJkda/2/, which looks like this:

<div class="circle"></div>

for(var count = 0; count < 20; count++){
  var ten = 10;
  ten = ten + 30;
  $(".circle").css({"width":ten+"px","height":ten+"px"});
};

How can I make this right? It seems to increase in width and height when I add the variable by any number such as 30 but doesn't bring out the result that it should.

like image 774
Joshua Waheed Avatar asked Mar 03 '26 03:03

Joshua Waheed


2 Answers

You need to define the ten variable outside the loop and create a new element for each ring.

For example,

var ten = 10;
var tgt = $('body');
for(var count = 0; count < 20; count++){
    ten += 30;
    tgt.append('<div class="circle" style="width:'+ten+'px;height:'+ten+'px;margin:-'+(ten/2)+'px 0 0 -'+(ten/2)+'px"></div>');
};

Notice that I also define the margin inside the javascript, since it also needs to change.

Your CSS needs a small change too;

.circle {
    position: absolute;
    top: 50%;
    left: 50%;
    border: 3px solid #666666;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-border-radius: 100%;
    -moz-border-radius: 100%;
    border-radius: 100%;
}

I have set the border radius to 100% instead of a pixel value, and removed the margin and width/height, which is unnecessary.

like image 56
Dave Avatar answered Mar 05 '26 15:03

Dave


First, move the variable declaration outside the loop. Second, set the border-radius value to 50%. Last, create a new element for every circle. Your code revisited:

/** 
 * css radius:
 *  -webkit-border-radius: 50%;
 *  -moz-border-radius: 50%;
 *  border-radius: 50%;
 */
var ten = 10;
for(var count = 0; count < 20; count++){
   ten = ten + 10;
   var c = $('<div class="circle"></div>').appendTo('body');
   c.css({"width":ten+"px","height":ten+"px"});
};

Modified jsFiddle

like image 31
KooiInc Avatar answered Mar 05 '26 17:03

KooiInc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!