0

Hi i need position to make fixed background with position absolute and on scroll change top. But my div jump all the time like here in demo

Has someone idea why?

d3tr1tus
  • 789
  • 2
  • 10
  • 23
  • Does this answer your question? [How to create parallax effect like this?](https://stackoverflow.com/questions/23178762/how-to-create-parallax-effect-like-this) – UfguFugullu May 07 '20 at 08:16
  • Unfortunately no because I can't make it with position fixed or with transform: translate I need top or margin-top but it jump like in demo :/ @UfguFugullu – d3tr1tus May 07 '20 at 09:02

1 Answers1

1

Your problem in your fiddle was the delta calculation of the scroll position. You need to use a fix top value of the container and not of the parallax image itself.

This example should work for you with some little performance improvements

var $window = $(window);

$window.on('scroll', pi);

function pi() {
  $('.parallax-image').each(function(index, element) {
    var $element= $(element);
    $element.css('top', parseInt($window.scrollTop()) - parseInt($element.parent().offset().top));
  });
}
.container {
  position: relative;
  display: block;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.parallax-image {
  width: 100vw;
  height: 100vh;
  position: absolute;
  left: 0;
  top: 0;
  background: url("https://htmlcolorcodes.com/assets/images/html-color-codes-color-tutorials-hero-00e10b1f.jpg") no-repeat center center;
  background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>First Test</p>
<div class="container">
  <div class="parallax-image"></div>
</div>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Second Test</p>
<div class="container">
  <div class="parallax-image"></div>
</div>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Third Test</p>
<div class="container">
  <div class="parallax-image"></div>
</div>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>

Supplement

You can use parallax images with pure CSS if you want. You find one example at w3schools.

UfguFugullu
  • 2,107
  • 13
  • 18