Last active
October 9, 2019 09:39
-
-
Save Aliath/cfb8f971143da0adf888fb0ddb34dc96 to your computer and use it in GitHub Desktop.
Plugin for creating parallax effects.
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
export default class Parallax { | |
elementsToAnimate = []; | |
// parseElements([HTMLElement, HTMLElement]) or parseElements([{element: HTMLElement, container: HTMLElement}]) | |
parseElements = normalizedList => { | |
this.elementsToAnimate = normalizedList.map(element => { | |
if (element instanceof HTMLElement) { | |
return { element, container: element.parentElement }; | |
} | |
return element; | |
}); | |
}; | |
// addElements([HTMLElement, HTMLElement, HTMLElement]) or addElements(HTMLElement) or addElement(NodeList) | |
addElements = list => { | |
let normalizedList = list; | |
if (list instanceof NodeList) { | |
normalizedList = [].slice.call(NodeList); | |
} else if (list instanceof HTMLElement) { | |
normalizedList = [list]; | |
} | |
this.parseElements(normalizedList); | |
}; | |
handleUpdate = () => { | |
this.elementsToAnimate.forEach(({ element, container }) => { | |
console.log(element.getBoundingClientRect().top); | |
const viewportTop = container.getBoundingClientRect().top; | |
const shouldBeFixed = viewportTop < 0 && container.offsetHeight - window.innerHeight + viewportTop > 0; | |
const percentageScrolled = -(viewportTop + element.offsetHeight) / (container.offsetHeight - window.innerHeight); | |
const transformTop = Math.round(percentageScrolled * innerHeight); | |
const calculatedStyles = { | |
position: 'fixed', | |
top: '0', | |
left: '0', | |
transform: `translateY(${transformTop}px)`, | |
}; | |
if (shouldBeFixed) { | |
Object.assign(element.style, calculatedStyles); | |
} else { | |
Object.keys(calculatedStyles).forEach(property => { | |
element.style.removeProperty(property); | |
}) | |
} | |
}); | |
}; | |
handleEvents = () => { | |
const EVENTS_TO_BIND = ['scroll', 'resize']; | |
EVENTS_TO_BIND.forEach(eventName => { | |
window.addEventListener(eventName, this.handleUpdate, false); | |
}); | |
}; | |
constructor(elements) { | |
this.addElements(elements); | |
this.handleEvents(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment