Scroll with two divs with different heights

Viewed 55

I'm want to scroll two divs at the same rate, basically if i've scrolled 25% of the first div, then the second will have scrolled the same percentage, but since they have different heights It is a bit hard to do. If anyone could help I'd be grateful.

var heightFirst = $('#first-div').height();
var heightSecond = $('#second-div').height();

$(window).scroll(function() {
  let offsetFirst = document.querySelector('#first-div').getBoundingClientRect().top;

  let offsetSecond = heightSecond * offsetFirst / heightFirst;

  if (offsetFirst <= 0) {
    document.getElementById('second-div').style.top = offsetSecond + 'px';
  }
  else if (offsetFirst >= 0) {
    document.getElementById('second-div').style.top = 200 + 'px';
  }
});
#background{
  height: 3000px;
}

#first-div {
  width: 200px;
  height: 1000px;
  position: absolute;
  top: 200px;
  background: #585f50;
}

#second-div {
  width: 100px;
  height: 3000px;
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  top: 200px;
  z-index: 10;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="background">
  <div id="first-div"></div>
  <div id="second-div"></div>
</div>

0 Answers
Related