Skip to content

Instantly share code, notes, and snippets.

@vwochnik
Last active October 23, 2020 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vwochnik/35ea4898cdb0c695d2f834f42f739c9e to your computer and use it in GitHub Desktop.
Save vwochnik/35ea4898cdb0c695d2f834f42f739c9e to your computer and use it in GitHub Desktop.
jQuery background moving blocks
license: mit

This is a version of moving blocks done with jQuery and CSS3 transitions for optimum performance and minimum dependencies for a project that already employs jQuery.

(function(jQuery) {
var $container, width, height;
function updateSize() {
var $window = $(window);
width = $window.width();
height = $window.height();
$container.css({
width: width,
height: height
});
}
function position(a, margin) {
var offset = a * (2 * width + 2 * height);
if (offset < width) return [offset, -margin];
offset -= width;
if (offset < height) return [width + margin, offset];
offset -= height;
if (offset < width) return [width - offset, height + offset];
offset -= width;
return [-margin, height - offset];
}
function spawnElement() {
var opacity = (0.3 + 0.7*Math.random()),
size = 0.08 * (width + height) * (1.0 - opacity),
duration = (1 - opacity) * 7,
p1 = position(Math.random(), size), p2 = position(Math.random(), size);
var $elem = $('<div/>')
.addClass('block')
.css({
left: p1[0], top: p1[1],
width: size, height: size,
marginLeft: -size/2, marginTop: -size/2,
opacity: opacity,
visibility: 'hidden',
transition: 'all '+duration+'s linear'
})
.on('transitionend', function() {
$elem.remove();
})
.appendTo($container);
setTimeout(function() {
$elem.css({
left: p2[0],
top: p2[1],
visibility: 'visible'
});
}, 100);
}
$(function() {
$container = $('#blocks');
$(window).on('resize', updateSize);
updateSize();
(function animation() {
setTimeout(function() {
requestAnimationFrame(animation);
spawnElement();
}, 100);
})();
});
})(jQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Moving Blocks</title>
<style>
body {
margin: 0;
}
.blocks-container {
position: relative;
overflow: hidden;
}
.block {
position: absolute;
background-color: #88a;
}
</style>
</head>
<body>
<div class="blocks-container" id="blocks"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="blocks.js" ></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment