【jQuery】How to implement a parallax animation that moves the background image in the opposite direction of scroll when scrolling (Control background-position-y property with JavaScript) | Demo page

※Please check using Developer tools

Sponsored links

CSS

body {
  height: 1000px;
}
.block {
  position: relative;
  width: 100%;
  height: 1500px;
}

.bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  background: url(/img/h.jpg) no-repeat center center;
  background-size: cover;
}
@media screen and (max-width:640px){
  .block {
    height: 500px;
  }
  .bg {
    background-size: contain;
  }
}
  

JavaScript

var scrollPos = $(window).scrollTop();
var scrollPrevPos = 0;
var bgPos = 0;

$(window).on("scroll", function() {
  scrollPos = $(window).scrollTop();
  var sectionLablesPos = $(".block").offset().top;
  var sectionLabelsHeight = $(".block").innerHeight();
  var delta = scrollPos - scrollPrevPos;
  if (scrollPos + window.innerHeight > sectionLablesPos && scrollPos < sectionLablesPos + sectionLabelsHeight) {
    console.log(delta);
    if (delta > 0) {
      bgPos = bgPos - 7;
    } else {
      bgPos = bgPos + 7;
    }
  }
    console.log(bgPos);
    $(".bg").stop(true, false).animate({
      "background-position-y": bgPos + "px",
    },1000);
  scrollPrevPos = scrollPos;
});