I'm using the following code to make some of my widgets on the sidebar to be sticky for a specific scroll and it works very well
<script>
window.onscroll = function () {
myFunction();
};
function between(x, min, max) {
return x > min && x <= max;
}
function myFunction() {
var w = actualWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth ||
document.body.offsetWidth;
var hest = document.documentElement.scrollTop;
var element = document.getElementById("mySidebar");
element.style.width = element.offsetWidth + 'px';
if ((w <= 992) || (hest <= 875)) {
element.style.position = "";
element.style.top = "";
return;
}
if (between(hest, 875, 2875)) {
element.style.position = "fixed";
element.style.top = "10px";
}
if (between(hest, 2875, 3855)) {
element.style.position = "relative";
element.style.top = "2015px";
}
if
(between(hest, 3855, 4855)) {
element.style.position = "fixed";
element.style.top = "-980px";
}
if
(between(hest, 4855, 6170)) {
element.style.position = "relative";
element.style.top = "3000px";
}
if
(between(hest, 6170, 6945)) {
element.style.position = "fixed";
element.style.top = "-2310px";
}
if
(between(hest, 6945, 8190)) {
element.style.position = "relative";
element.style.top = "3785px";
}
if
(between(hest, 8190, 9545)) {
element.style.position = "fixed";
element.style.top = "-3510px";
}
if
(between(hest, 9545, 10860)) {
element.style.position = "relative";
element.style.top = "5175px";
}
if (hest > 10860) {
element.style.position = "fixed";
element.style.top = "-4814px";
}
};
</script>
The problem is while scrolling, it causes a layout shift. Especially, when the position changes from fixed to relative or relative to fixed.
I used sticky instead of fixed, but still, I got the same layout shift.
How to fix this CLS?
Regards,