Wouter Comello Wouter Comello - 1 month ago 9
Javascript Question

Why does my images jump a few pixels when executing this parallax script?

I am not a javascript guy so I dont really understand why my code does this:

When first loading the page and scrolling, the image targeted jumps up down about 30px

var parallax = document.querySelectorAll(".headerphotosmall, .headerphoto"),
speed = 0.9;

window.onscroll = function(){
[].slice.call(parallax).forEach(function(el,i){

var windowYOffset = window.pageYOffset,
elBackgrounPos = "50%" + (windowYOffset * speed) + "px";

el.style.backgroundPosition = elBackgrounPos;

});
};


video showing my problem: https://i.gyazo.com/040f328ac78a5d5243e37352e19e0cf6.mp4

Answer

I think @BeyelerStudios's comment explains the problem... The initial position of your images aren't related to the initial scroll position.

I don't know what is a parallax, though...

Since I don't know your CSS, I tried to auto-update the position of your parallax images when the script runs, with that Array#forEach loop. If you're declaring these background images later, then you need to wait the page to load.

var parallax, speed;
var updateBgImagePos, updateParallaxPosition;

// Converts parallax HTML collection to
// Array
parallax = [].slice.call(
    document.querySelectorAll(".headerphotosmall, .headerphoto")
);

speed = 0.9;

updateBgImagePos = function(el, i) {
    var windowYOffset = window.pageYOffset,
        elBackgrounPos = "50%" + (windowYOffset * speed) + "px";

    el.style.backgroundPosition = elBackgrounPos;
};

updateParallaxPosition = function() {
    parallax.forEach(updateBgImagePos);
};

window.onscroll = updateParallaxPosition;

// If your script is declared later than the images,
// you don't need to wait the page to load  to
// get/modify them.
updateParallaxPosition();