Roland
Roland

Reputation: 9721

How to make this shake effect behave?

I have the following piece of code:

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;
};

The problem is that when I apply it, if the object is positioned absolutely in the center, it makes the object jump to the left of the page.

Can this be fixed? and how if it can?

Upvotes: 0

Views: 211

Answers (2)

James Montagne
James Montagne

Reputation: 78720

You are setting $(this).css("position","relative");. By setting position: relative, you are moving the element back into the document flow wherever it may belong, and then positioning it relative to that position.

In the case of absolutely positioned elements, you will need to keep them absolute and calculate the movement based on their current positions.

Upvotes: 1

musefan
musefan

Reputation: 48435

I think using "margin-left" instead of "left" in your animate styles will have a better effect. You may need to play around with relative positioning etc. if it does not work first time

Upvotes: 3

Related Questions