0

I want my .row-navigation row to be position-fixed when scrolled. So i used window.onscroll to listen to the scroll event and assign the class .sticky , to .row-navgation row , when scrolled. In the process getBoundingClientRect().top is used.

The unexpected behaviour:
When the scroll event takes places then getBoundingClientRect().top returns 0 with each alternate pixel scroll.
As a result The .row-navigationrow flickers when scrolled

Check this on codepen https://codepen.io/neel111/pen/NVaEyB


<div class="container">
  <div class="row-welcome"></div>
  <div class="row-navigation"></div>
</div>

.row-welcome {
  height: 34px;
  background-color: yellow;
}
.row-navigation {
  height: 80px;
  background-color: #000;
}

.row-navigation.sticky {
    position: fixed;
    top: 0;
    width: 100%;
}
window.onscroll = function() {
    var rowNavigation = document.querySelector('.row-navigation');
    var nextDomElement = rowNavigation.parentElement.nextElementSibling;

    console.log(rowNavigation.getBoundingClientRect().top, rowNavigation.getBoundingClientRect().right, rowNavigation.getBoundingClientRect().bottom);  

    if (0 > rowNavigation.getBoundingClientRect().top) {
      rowNavigation.classList.add('sticky');
    } else {
      rowNavigation.classList.remove('sticky');
    }
}

How to fix the unexpected behaviour of getBoundingClientRect().top?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jake
  • 244
  • 2
  • 16
  • 2
    You're assigning `top:0` yourself using the `sticky` class. – Geert-Jan May 21 '19 at 06:38
  • @Geert-Jan Oh shit! That's a silly and naive mistake. I presume the `top:0` is necessary in the `sticky` class. How can i make it work smoothly? – Jake May 21 '19 at 06:41
  • If you want to check if the window has scrolled at all use `window.scrollY` instead in your condition – Geert-Jan May 21 '19 at 06:43

0 Answers0