Infra Stank
Infra Stank

Reputation: 816

CSS Transform jquery animation not working as expected

In an answer to another question I made a simple bit of code to animate the rotation of a PNG as you scrolled down the page. That worked fine but on reversing the animation on the up-scroll didn't work properly.

Expected would be that the PNG would go back to it's original position but it falls short by a couple of pixels .

fiddle : http://jsfiddle.net/EnSkJ/3/

code :

var sdegree = 0;


var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       sdegree += 1;
    var srotate = "rotate(" + sdegree + "deg)";
    $("img").css({"-moz-transform" : srotate, "-webkit-transform" : srotate});
   } else {
      sdegree -= 1;
    var srotate = "rotate(" + sdegree + "deg)";
    $("img").css({"-moz-transform" : srotate, "-webkit-transform" : srotate});
   }
   lastScrollTop = st;
});

Upvotes: 1

Views: 1564

Answers (1)

Jasper
Jasper

Reputation: 76003

You are increasing the rotation of the element on scroll, but you are not taking into account how far the user scrolled.

You should re-write your code so that instead of always adding or subtracting one degree from the rotation, calculate the amount of rotation based on how far the user has scrolled. That way you can set beginning and end points where your element will always be at the same rotation at those points.

Update

A simple example of what I'm talking about is here:

$(window).scroll(function(event){
   var srotate = "rotate(" + $(this).scrollTop() + "deg)";
   $("img").css({"-moz-transform" : srotate, "-webkit-transform" : srotate});
});

Here is a demo: http://jsfiddle.net/EnSkJ/4/

Since this code rotates the element based on the scroll position, the rotation will always be the same at the same scroll position.

Update

Also you can detect what browser is being used and only update the proper vender-prefixed transform property:

var venderPrefix = ($.browser.mozilla) ? '-moz-' :
                   ($.browser.webkit) ? '-webkit-' : 
                   ($.browser.msie) ? '-ms-' : 
                   ($.browser.opera) ? '-o-' : '';

$(window).scroll(function(event){
   $("img").css(venderPrefix + "transform", "rotate(" + $(this).scrollTop() + "deg)");
});

Here is a demo: http://jsfiddle.net/EnSkJ/6/

Upvotes: 3

Related Questions