SO, MoveIt
by acbabis
HTML
<div id='div1'></div>
CSS
#div1{
width:10px;
height:10px;
position:absolute;
background:red;
}
JavaScript
$(function()
{
var methods =
{
init : function(options) {
$(this).each(function() {
var self = $(this);
var settings = $.extend({
top : 50,
left : 50,
dir : true,
}, options);
var i=0, j=0;
var move = function()
{
settings = self.data('moveItTarget');
if(settings.dir)
{
i++;
j++;
}
else
{
i+=10;
j+=10;
}
self.css({'top':Math.min(i, settings.top), 'left':Math.min(j, settings.left)});
if(j<=settings.top && i<=settings.top)
{
setTimeout(move,1);
} else {
self.data('movingIt', false);
}
};
self.data('moveItTarget', settings);
if(!self.data('movingIt')) {
self.data('movingIt', true);
move();
}
});
}
};
$.fn.moveIt = function(methodOrOptions) {
if (methods[methodOrOptions]) {
return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof methodOrOptions==='object' || !methodOrOptions) {
return methods.init.apply(this, arguments);
} else {
$.error('Method "'+methodOrOptions+'" does not exist!');
}
};
}(jQuery));
$('#div1').moveIt({ top: 100, left: 100, dir: true }); // first call
$('#div1').moveIt({ top: 300, left: 300, dir: false }); // second call