Mathieu Préaud
Mathieu Préaud

Reputation: 409

Convert jQuery scrollTop to Javascript to invert scroll direction

I'm trying to convert some jQuery code to Vanilla JS. The purpose is to invert the scroll direction of a container. The jQuery version works fine. However I'm struggling to convert it in JS.

$(window).on('scroll',function(){
    $(".container").css('bottom',$(window).scrollTop()*-1);
});

The JS:

const container = document.querySelector('.container');

var scroll =  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

window.addEventListener('scroll', function() {
    container.style.bottom = "";
});

Thank you.

Upvotes: 0

Views: 77

Answers (1)

Davi
Davi

Reputation: 4147

You might want to consider working with CSS position:fixed and without JS. Otherwise, as I said in the first comment:

1.) Make a function that returns the current scroll position

function getScrollPosition() {
  return Math.max(
    window.scrollY, // same as window.pageYOffset
    document.documentElement.scrollTop,
    document.body.scrollTop
  );
}

2.) On each scroll event call the function

window.addEventListener('scroll', function () {
  const scrollY = getScrollPosition();
  // ... rest elided ...
});

3.) Assign the returned value/scroll position with a negative multiplication (* -1) to the .style.bottom property on the container, don't forget to tack "px" onto the value

window.addEventListener('scroll', function () {
  const scrollY = getScrollPosition();
  container.style.bottom = -1 * scrollY + 'px'; // doesn't matter if " or ' is used
});

Try it:

Hint: Use the devtools to see the inline styles being updated on the container element

const container = document.querySelector('.container');

function getScrollPosition() {
  return Math.max(
    window.scrollY, // same as window.pageYOffset
    document.documentElement.scrollTop,
    document.body.scrollTop
  );
}

window.addEventListener('scroll', function () {
  const scrollY = getScrollPosition();
  container.style.bottom = -1 * scrollY + 'px'; // doesn't matter if " or ' is used
});
body {
  min-height: 110vh;
}

.container {
  position: absolute;
  bottom: 0;
  left: calc(50% - 100px);
  width: 200px;
  height: 200px;
  border: 1px solid red;
}
<div class="container">
  I move
</div>

Upvotes: 1

Related Questions