Last active
November 25, 2020 17:58
-
-
Save michaelgarydean/aa9ea80c28b7124fb6e98751cc8b4424 to your computer and use it in GitHub Desktop.
Vanilla Javascript parallax scrolling of CSS grid items.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @description | |
* Vanilla Javascript parallax scrolling of items. | |
* | |
* @author Michael Gary Dean <contact@michaeldean.ca> | |
* @see https://codepen.io/RichBarber/pen/gdjPzv | |
*/ | |
window.addEventListener('scroll', function() { | |
//elements from the DOM | |
let gridDiv = document.getElementById('featured-content-grid-wrapper'); //the div that is styled as display: grid | |
var gridChildren = gridDiv.children; //the divs that contain each grid item | |
//Calculate offset of grid item while scrolling | |
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; | |
let oddPos = scrollTop / 3 + 'px'; | |
let evenPos = scrollTop / 2.5 + 'px'; | |
//by default, we assume it's an odd column to set the speed. | |
var currentOffset = oddPos; | |
//Transform CSS for element | |
for (var childIndex = 1; childIndex <= gridChildren.length; childIndex++) { | |
currentChild = gridChildren[childIndex]; | |
//Set a different speed depending on if the child is in an even or odd column | |
if(childIndex % 2 == 0) { | |
currentOffset = evenPos; | |
} | |
//Offset the grid item | |
currentChild.style.transform='translateY(' + currentOffset + ')'; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment