jQuery shake() function December 29, 2009
I needed a quick function for jQuery to shake an absolute or static positioned (can be easily modified to support other positions too, but it doesn’t at the moment) element up&down that isn’t depended on jQuery UI (I’m using to shake simplemodal‘s container).
This is what I came up with that:
1 2 3 4 5 6 7 8 9 10 11 | (function($){ $.fn.shake=function(opt){ opt=$.extend({times: 8,delay: 150,pixels: 20},opt||{}); $(this).each(function(){ var orig=parseInt($(this).css('top')); for (var i=0; i<opt.times; i++) $(this).animate({top:orig+(opt.pixels*(i%2==0?1:-1))},opt.delay); $(this).animate({top:orig},opt.delay); }); } })(jQuery); |
Its usage looks like that:
$('#simplemodal-container').shake({times:8, delay:150, pixels:20});
All the parameters are optional, you could simply call $(..).shake() to use the defaults values or overwrite just some of the them.
times determines how many times to shake the element, delay is how long each animate() call should take, and pixels is the number of pixels to move up/down every time
Leave a Reply