Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radiating circle effect using CSS and Javascript

I'm trying to create a radiating circles effect using CSS and Javascript. My idea was to create a new copy of the circle at an interval, then removing them after a few seconds.

It works well for a couple of seconds, but then it seems like the circles are being removed too quickly, as they do not radiate for more than a moment.

What's happening? Is there a better way to accomplish the effect that I get for the first couple of seconds?

CSS

.circle {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  border: 3px solid #000;
  -webkit-transition: all 2s linear;
  -webkit-transform: scale(0.1);
  position: absolute;
  top: 0;
  left: 0;
}

.circle.zoom {
  opacity: 0;
  -webkit-transform: none;
}

Javascript

counter = 0;

function createCircle(){
  // Circle ID  
  var circleID = "circle_" + counter;

  // Add circle to document
  $("body").append("<div class='circle' id='" + circleID + "'></div>");
  $thisCircle = $("#" + circleID);

  // add "zoom" class
  setTimeout(function(){
      $thisCircle.addClass("zoom");
  },10);

  // Remove circle
  setTimeout(function(){
      $thisCircle.remove();
  },3000);
  counter++;
}

setInterval(function(){
    createCircle();
},500);

JSFiddle Demo: http://jsfiddle.net/YaKBH/9/

like image 680
Chris Herbert Avatar asked Oct 22 '22 01:10

Chris Herbert


2 Answers

You forgot to make the $thisCircle variable local to your closure scope, it is an implicit global. After the 3 seconds, it will start removing the current circle (that has been animated for 500 ms). The circles 0 to 4 will stay in the DOM, with opacity: 0.

To fix this, just add another var keyword:

  var $thisCircle = $("#" + circleID);

(updated demo)


Btw, you could omit that counter variable and directly reference the element that was just created:

setInterval(function createCircle() {
    var $thisCircle = $("<div class='circle'></div>").appendTo("body");
    // add "zoom" class with minimal delay so the transition starts
    setTimeout(function () {
        $thisCircle.addClass("zoom");
    }, 0);

    // Remove circle
    setTimeout(function () {
        $thisCircle.remove();
    }, 3000);
}, 500);

(demo)

like image 163
Bergi Avatar answered Oct 27 '22 11:10

Bergi


Here's a better solution. CSS gives you selectors that allow you to drop the counter altogether.

http://jsfiddle.net/YaKBH/13/

You can append the circle without assigning it an ID.

$("body").append("<div class='circle'></div>");

Since you want to zoom the circle you just added, it'll be the last circle when you query the circles.

$(".circle:last-child").addClass("zoom");

When it's time to remove the circle, you're removing the oldest circle, which would be first in queue.

$(".circle:first-child").remove();
like image 28
Overcode Avatar answered Oct 27 '22 10:10

Overcode