Skip to content

Instantly share code, notes, and snippets.

@AndrewHaine
Last active April 4, 2017 21:11
Show Gist options
  • Select an option

  • Save AndrewHaine/04bc0d33d740d70528e2120cbdecf422 to your computer and use it in GitHub Desktop.

Select an option

Save AndrewHaine/04bc0d33d740d70528e2120cbdecf422 to your computer and use it in GitHub Desktop.
Smooth background image parallax effect - requires jquery
class Parallax {
constructor(el) {
if(!el.length) {
return;
}
else {
this._doParallax(el);
}
}
_doParallax(el) {
// Scoped variable to store animation frame ID
let animId;
// Begin the scroll event
$(window).scroll(() => {
// Grab some required values from the DOM
let scrollBottom = $(window).scrollTop() + $(window).height(),
topOffset = el.offset().top,
dowTop = $(window).scrollTop() - 170;
// Define the scroll function for use later
const updateScroll = () => {
// Calculate the distance from the top of the window to the top of the target
let distance = dowTop - topOffset;
// Calculate how far by percentage into the scrollable area we are
let calcPercentage = (distance / $(window).height()) * 100;
// Set the background image position
el.css('background-position', `50% ${(100 - calcPercentage) - 100}%`);
}
// If we are inside the scrolling area start the parallax effect
if (scrollBottom > topOffset && dowTop < topOffset) {
// Request animation frame for performance boost
animId = requestAnimationFrame(updateScroll);
} else {
// Cancel the animation frame if we are outside the target area
window.cancelAnimationFrame(animId);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment