Skip to content

Instantly share code, notes, and snippets.

@seutje
Created March 23, 2011 12:27
Show Gist options
  • Save seutje/883027 to your computer and use it in GitHub Desktop.
Save seutje/883027 to your computer and use it in GitHub Desktop.
Make stuff hover around like balloons or something, assumes elements are already positioned absolute with top and left/right values.
;(function($){
$.fn.balloons = function(options) {
var balloons = this,
cssAnim = Modernizr && Modernizr.cssanimations,
opts = $.extend({}, $.fn.balloons.defaults, options),
/* Helper function to return random range */
getRand = function(min, max) {
return Math.floor(Math.random() * (min-max+1)) + max;
},
/* Main movement function */
moveBalloons = function() {
var ele = arguments[0] ? arguments[0] : $(this);
$w = $(window),
winh = $w.height(),
winw = $w.width();
/* Make sure we got a jQuery collection */
ele = ele instanceof jQuery ? ele : $(ele);
/* Move each element separately */
ele.each(function(i, el) {
var balloon = $(el),
bwidth = balloon.width(),
bheight = balloon.height(),
lpos = parseInt(balloon.css(opts.side)),
tpos = parseInt(balloon.css('top')),
ldis = getRand(-opts.speed, opts.speed),
tdis = getRand(-opts.speed, opts.speed),
lnew = lpos + ldis,
tnew = tpos + tdis,
pos = {},
rmost = opts.side == 'left' ? lnew + bwidth : lnew,
duration = getRand(opts.min, opts.max);
pos[opts.side] = (lnew > 0 && rmost < winw) ? lnew : lpos;
pos.top = (tnew > 0 && (tnew + bheight) < winh) ? tnew : tpos;
if (cssAnim) {
pos['-webkit-transition-duration'] = pos['-moz-transition-duration'] = pos['transition-duration'] = duration + 'ms';
balloon.css(pos);
setTimeout(moveBalloons, duration, [balloon]);
}
else {
balloon.animate(pos, duration, 'linear', moveBalloons);
}
});
};
if (cssAnim) {
this.css({
'-webkit-transition-property': 'top, ' + opts.side,
'-moz-transition-property': 'top, ' + opts.side,
'transition-property': 'top, ' + opts.side,
'-webkit-transition-timing-function': opts.easing,
'-moz-transition-timing-function': opts.easing,
'transition-timing-function': opts.easing
});
}
/* Initiate */
moveBalloons(this);
/* Return collection */
return this;
};
$.fn.balloons.defaults = {
speed: 150, /* max change in px for a single interval */
min: 3000, /* min delay in ms */
max: 5000, /* max delay in ms */
side: 'left', /* attribute to manipulate, left or right */
easing: 'linear' /* easing to use for the animations */
}
})(jQuery);
@seutje
Copy link
Author

seutje commented Mar 29, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment