Skip to content

Instantly share code, notes, and snippets.

@fojas
Created August 19, 2011 23:50
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 fojas/1158340 to your computer and use it in GitHub Desktop.
Save fojas/1158340 to your computer and use it in GitHub Desktop.
Flying block
(function($){
$.extend($.fn,{
blockit: function(options){
new BlockIt(this, options);
return this;
}
});
var BlockIt = function(el, options){
var options = options || {},
posLeft = (options['left'] || (this.offset(el).left + (el.width()/2))) - 24,
posTop = (options['top'] || (this.offset(el).top + (el.height()/2))) - 24;
this.position = [posLeft,posTop]
this.windowSize = [$('body').width(), $('body').height()]
this.showTarget();
var that = this;
setInterval(function(){that.fire.call(that)},300);
};
$.extend(BlockIt.prototype,{
offset : function(el){
var _offset = {};
this.offset = function(el){
var s = el
_offset[s] = _offset[s] || el.offset();
return _offset[s]
};
return this.offset;
}(),
showTarget : function(){
var target = $('<img src=http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/48x48/target.png />');
target.css({
'position' : 'absolute',
'left' : this.position[0] + 'px',
'top' : this.position[1] + 'px'
});
$('body').append(target);
},
coinFlip : function(){
return !!parseInt(Math.random() * 2, 10);
},
fire : function(){
var d = $('<div />');
if(this.coinFlip()) {
// coming from left or right
d.css({
"top" : parseInt(Math.random()*this.windowSize[1],10) + 'px',
"left" : (this.coinFlip() ? (-25) : (this.windowSize[0] + 25) ) + 'px'
});
} else {
// coming from top or bottom
d.css({
"left" : parseInt(Math.random() * this.windowSize[0],10) + 'px',
"top" : (this.coinFlip() ? (-25) : (this.windowSize[1] + 25) ) + 'px'
});
}
d.css({
"position" : "absolute",
"height" : "10px",
"width" : "10px",
"border" : "1px solid green"
});
$('body').append(d);
var that = this;
setTimeout(function(){
d.animate({
"top" : (19+that.position[1]) + "px",
"left" : (19+that.position[0]) + "px"
}, 6000,function(){$(this).remove()});
}, 300);
}
});
})(jQuery);
javascript:(function(){var d = document;if(window.jQuery){jQuery.getScript('https://raw.github.com/gist/1158340/blockit.js')}})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment