I'm learning how to create a scroll parallax effect following this guide. So far so good, but then I realize that my background position is set to '50%'(center). So when I run my js, the background position unit is changed from % to px hence it position is not what I expected.
How can I write the code so the background position change in percentage?
Here is the code:
window.addEventListener('scroll', function(){
var scrollPosition = window.pageYOffset;
var bgParallax = document.getElementsByClassName('parallax')[0];
var limit = bgParallax.offsetTop + bgParallax.offsetHeight;
if (scrollPosition > bgParallax.offsetTop && scrollPosition <= limit){
bgParallax.style.backgroundPositionY = scrollPosition / 2 + 'px';
}else{
bgParallax.style.backgroundPositionY = '0';
}
});
body{
margin:0px;
padding:0px;
height:600px;
}
.parallax{
width:100%;
height:300px;
background-color:red;
background-image:url('http://68.media.tumblr.com/9c811fb09ae9fe61e3bbcb1d7f0c3724/tumblr_o9489fIsmH1qhttpto3_1280.png');
background-position:center;
}
<div class='parallax'></div>
And here is a CODEPEN
PPD: I can't change my html or css and I need solve this with pure javascript for learning purposes.
Something like this?
It's essentially the same thing, just starting at 50% instead of 0px, and subtracting as you scroll down, depending on how far the image should move. (10% in this case, so backgroundPositionY
varies from 40% to 50%)
window.addEventListener('scroll', function(){
var scrollPosition = window.pageYOffset;
var bgParallax = document.getElementsByClassName('parallax')[0];
var limit = bgParallax.offsetTop + bgParallax.offsetHeight;
if (scrollPosition > bgParallax.offsetTop && scrollPosition <= limit){
bgParallax.style.backgroundPositionY = (50 - 10*scrollPosition/limit) + '%';
}else{
bgParallax.style.backgroundPositionY = '50%';
}
});
body{
margin:0px;
padding:0px;
height:600px;
}
.parallax{
width:100%;
height:300px;
background-color:red;
background-image:url('http://68.media.tumblr.com/9c811fb09ae9fe61e3bbcb1d7f0c3724/tumblr_o9489fIsmH1qhttpto3_1280.png');
background-position:center;
}
<div class='parallax'></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With