Skip to content

@nick-jonas /bubbles-dom.js
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Animating bubbles using the transform property on multiple DOM elements
// updates the position of a bubble element
updatePosition: function($elem, x, y){
var value = 'translate3d(' + x + 'px, ' + y + 'px, 0.1px)';
// use Modernizr to get all the vendor prefixes
value = Modernizr._prefixes.join('transform' + ':' + value + '; ');
value = value.split(';');
var props = {};
// create an object to apply the vendor prefixed CSS properties
for(var i = 0; i < value.length; i++){
var thisVal = value[i].split(':');
if(thisVal.length === 2){
props[thisVal[0]] = thisVal[1];
}
}
$elem.css(props);
},
// create bubbles
createBubbles: function(){
var self = this,
el = this.element,
width = $(window).width(),
height = $(window).height(),
docFrag = document.createDocumentFragment(),
bubbles = [];
for(var i = 0; i < this.settings.bubbleCount; i++){
// create div element
var bubble = document.createElement('div');
bubble.className += 'bubble';
// create random properties
var diam = (Math.random() * (this.settings.maxDiam - this.settings.minDiam)) + this.settings.minDiam,
x = Math.floor(Math.random() * width),
y = height + (diam / 2) + Math.random() * 100,
speed = (Math.random() / 2) + 0.1,
amplitude = (Math.random() * 50) + 45,
isOutline = false;
// store bubble data in memory
var bubbleData = {
elem: bubble,
startX: x,
x: x,
y: y,
radius: diam / 2,
speed: speed,
opacity: Math.random() * 0.4,
amplitude: amplitude,
isOutline: isOutline
};
bubbles.push(bubbleData);
// apply static properties - these won't change as we animate
bubble.style.opacity = bubbleData.opacity;
bubble.style.width = diam;
bubble.style.height = diam;
docFrag.appendChild(bubble);
}
// add the container to the document
el.appendChild(docFrag);
var count = 0;
function animate(){
count++;
for(var i = 0; i < bubbles.length; i++){
var b = bubbles[i];
// if reached top, send back to bottom
if(b.y <= b.radius * -2){
b.y = window.innerHeight + b.radius;
}
b.y = b.y - b.speed;
b.x = b.startX + Math.sin(count / b.amplitude) * 50;
self.updatePosition($(b.elem), b.x, b.y);
}
}
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
(function animloop(){
requestAnimFrame(animloop);
animate();
})();
}
@nick-jonas
Owner

and the CSS for the bubbles:

#bubbles div, #bubbles-top div {
  width: 60px;
  height: 60px;
  background: #5ecaff;
  border-radius: 50%;
  position: absolute;
}

#bubbles div.outline, #bubbles-top div.outline {
  background: transparent;
  border: 2px solid #5ecaff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.