Implementing jQuery's shake effect with animate

wmitchell picture wmitchell · Dec 9, 2010 · Viewed 33.1k times · Source

I've been given a cut down subset of the jQuery lib one of the key features I'm missing is the .effect functions. I do however have .animate. I was wondering if anyone would have any ideas how I could go about reproducing the animation functions.

I am particularly consious of making this only a few lines as I need to keep the code size down. Which is why the jquery lib is as small as it is and doesnt have the effects functions.

TLDR - I'm trying to replace

 $("#"+id_string).effect( "shake", {}, "fast" );

With something using .animate within jQuery.

Answer

wmitchell picture wmitchell · Dec 9, 2010

So far I have something like this ..

jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
    this.each(function() {
        $(this).css("position","relative"); 
        for (var x=1; x<=intShakes; x++) {
        $(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
    .animate({left:intDistance}, ((intDuration/intShakes)/2))
    .animate({left:0}, (((intDuration/intShakes)/4)));
    }
  });
return this;
};