Reputation: 113
So, I'm trying to animate elements (sequentially and independently) based on their scroll position.
The goal is to loop through each element, and change it's rotation based on the users scroll position. Right now, the rotations on each item are always the same. How can this be achieved?
Here is a Fiddle: https://jsfiddle.net/nfquerido/wy84pLud/
And this is the loop function:
var _items = function () {
forEach(items, function(item) {
var scrollTop = _scrollTop(),
elementTop = item.offsetTop,
documentHeight = _getDocumentHeight(),
elementHeight = _getElementHeight(item),
// Transform the item based on scroll
rotation = (scrollTop / (documentHeight - windowHeight) * 360),
transform = 'rotate(' + rotation + 'deg)';
// Elements off the top edge.
if (scrollTop > elementTop) {
item.classList.add('scrolling');
item.style.webkitTransform = transform;
} else {
item.classList.remove('scrolling');
item.style.webkitTransform = null; // Reset the transform
}
});
};
I'd appreciate vanilla JavaScript suggestions only please!
Upvotes: 2
Views: 2458
Reputation: 202
I think this is the fix you're looking for:
I added this right above your assignment of the rotation var:
// Transform the item based on scroll
rotationFactor = Math.max(0, scrollTop - elementTop),
rotation = ( rotationFactor / (documentHeight - windowHeight) * 360),
After replacing this they each get their relative offset rotation :)
The error is that the only changing/affecting variable to the rotation was your scrollTop, while that is only on a document-level. To effect on an element-level we also want to include that difference :)
Upvotes: 2