Freeman
Freeman

Reputation: 1190

Animation starts moving out of position after some time

I am trying to create a sort of slideshow animation. I have the codes here: jsFiddle.

These tablets would rotate around.

The problem is that, at random times, the animation will move out of line. The wrong tablets undergo wrong animations. Here are the screenshots:

When everything is fine

And this is how it looks like when the animations goes wrong

when the animation goes wrong

The main problem is I don't understand why the animation would go wrong random times. In my computer it will run properly for hours, but in other cases (especially on Safari).

Upvotes: 4

Views: 560

Answers (4)

wheresrhys
wheresrhys

Reputation: 23560

You could store the expected final css values for each animated el and then in the animate callback set these values, so for each animated el something like

var el = $(selector);

el.data("finalCSS", { your expected final CSS values })

$("selector").animate({animation properties}, function() {
     el.css(el.data("finalCSS")).data("finalCSS", undefined);
})

This doesn't help with figuring out why it's happening (but I can't recreate the issue myself), but provides a failsafe to make sure the layout doesn't break;

Upvotes: 2

RSG
RSG

Reputation: 7123

You can do this with far less code and far fewer headaches.

1. Store your tablet position attributes in classes

.tablet1{
  height:100px;
  width:140px;
  margin-left:-540px;
  top: 200px;
  z-index:10;
} 

2. Use a general function to handle all your transitions.

JQuery UI will do all the work for you if you use switchClass

switchTabletsRight = function(){
  var i, next, max = 5;
  for(i = 1; i <= max; i++){
    next = (i < max)? i + 1 : 1;
    $(".tablet" + i).switchClass("tablet" + i, "tablet" + next);
  }
};​

Here's the JSfiddle proof of concept: http://jsfiddle.net/nRHag/4/

Upvotes: 1

Louis Ricci
Louis Ricci

Reputation: 21106

You are setting CSS positions to decimal values.

    img_w = $("#tablet"+num+" img").width();
    img_w = img_w *140 / 600;
    img_h = $("#tablet"+num+" img").height();
    img_h = img_h *140 /600;
    ...
    var new_width = $(this).width() * 140 / 600;
    $(this).css('width', new_width);
    var new_height = $(this).height() * 140 / 600;
    $(this).css('height', new_height);

Your division could be cause decimal results which have different effects in different browsers. Sub pixel CSS positioning may be creating your unintended errors.

Upvotes: 0

Sandeep
Sandeep

Reputation: 819

I believe this happens when you try to animate before the previous animation has ended. Use jQuery stop() just before you animate. For example:

$('#animatingDiv').stop(false, true).animate({height:300}, 200, callback);

The first param(false) will empty the animation queue on that element and the second param(true) will jumps to the end of current animation before starting a new animation.

Upvotes: 1

Related Questions