I created Parallax script for some elements (rect & circles) so when I scroll from top to bottom, elements should move to the top
Elements starting position is added in HTML directly using < style > The problem is when I scroll back elements move down, but they are not in the same starting position when I reach the top of the page.
HTML:
<img style="top: 62%; left: 46.3%;" class="l-parallax_item" src="./path/to/img">
<img style="top: 74%; left: 42.7%;" class="l-parallax_item" src="./path/to/img">
CSS: Parent has position relative, l-parallax_item is position absolute
JS:
var parallaxElements = document.getElementsByClassName("l-parallax_item");
var lastScrollTop = 0;
window.onscroll = function() {
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
console.log("bottom");
for(i = 0; i < parallaxElements.length; i++) {
var position = parallaxElements[i].offsetTop;
var movePx = parallaxElements[i].getAttribute("data-px-per-scroll");
parallaxElements[i].style.top = (position - parseInt(movePx))+"px";
}
} else {
console.log("top");
for(i = 0; i < parallaxElements.length; i++) {
var position = parallaxElements[i].offsetTop;
var movePx = parallaxElements[i].getAttribute("data-px-per-scroll");
parallaxElements[i].style.top = (position + parseInt(movePx))+"px";
}
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}
I noticed when I scroll from top to bottom I get more console.log("bottom") messages. * When I scroll top > bottom and vise versa. So I guess that is the reason why the element is not in the same position too when I go bottom > top.
How can I fix this?
EDIT: http://jsfiddle.net/r9751p8q/6/ Try to scroll to the bottom and then back you will see that some element disappear