5

I want to fix an elements position when it's perfectly centered. Currently it's being fixed when it's fully visible and hence snaps to the center. - Can I somehow observe when the element is centered?

const box = document.querySelector(".box");

const obs = new IntersectionObserver(entries => {
  if (entries[0].isIntersecting) {
    box.style.position = "fixed";
    box.style.top = "50%";
    box.style.transform = "translateY(-50%)"
  }
}, {threshold: 1})

obs.observe(box);
.v-detail__video {
  width: 100vw;
  height: 300vh;
  display: flex;
  padding-top: 70vh;
  justify-content: center;
}

.box {
  background-color: black;
  width: 50vw;
  height: 200px;
}
<div class="v-detail__video">
  <div class="box"></div>          
</div>
Tom
  • 3,672
  • 6
  • 20
  • 52

0 Answers0