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-navigation
row 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
?