Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active July 4, 2018 04:03
Show Gist options
  • Save kjbrum/6bedf4b2355f5a487fdb611c92384691 to your computer and use it in GitHub Desktop.
Save kjbrum/6bedf4b2355f5a487fdb611c92384691 to your computer and use it in GitHub Desktop.
Easy parallax with a few lines of JavaScript.
// Initialize Parallax
var parallax_el = document.querySelectorAll('[data-parallax]');
var speed = 0.25;
function updateElementPosition() {
[].slice.call(parallax_el).forEach(function(el,i) {
var speed = el.dataset.parallax || 0.25;
var offset = (-(window.pageYOffset - el.offsetTop) * speed);
el.style.transform = 'translate3d(0, ' + offset + 'px, 0)';
el.style.OTransform = 'translate3d(0, ' + offset + 'px, 0)';
el.style.msTransform = 'translate3d(0, ' + offset + 'px, 0)';
el.style.MozTransform = 'translate3d(0, ' + offset + 'px, 0)';
el.style.WebkitTransform = 'translate3d(0, ' + offset + 'px, 0)';
});
}
if(window.innerWidth > 1024) {
updateElementPosition();
window.onscroll = function() {
updateElementPosition();
}
}
// Doesn't quite work...
// $.fn.parallax = function(strength) {
// var scroll_top = $(window).scrollTop();
// var move_value = Math.round(scroll_top * strength);
// this.css('background-position', 'center -'+ move_value +'px');
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment