'What's the best way to track the y position of an html element when the elements above change?
Kia ora.
I'm working on a salesforce CMS hostd site, using lightnign web components.
One of my components is a "sticky ad". It sits at the bottom of a column and is relatively positioned, until we scroll past it, then it becoems fixed until you scroll back up past its original y position.
That is the intended result, however initially the code checked its initial y position once when the user first scrolls and then keeps that number for the rest of the components life. However if the user scrolls before all of the elements on the page have loaded this y value can be incorrect, leading to the component getting fixed much earlier than when we actually scroll to it, and covering up elements above it. additionally, the elements above it sometimes change in size, which causes the same issue.
I have a solution but it feels hacky and not ideal.. here are soem code snippets:
<template>
<div class='placeholder'>
<div class='container'>
<template if:true={readyToDisplay}>
{displayAd}
</template>
</div>
</div>
</template>
Partial js:
_onScroll() {
if (this.stickyAd) {
// reduce performance cost by only checking positon every 10 scrolls.
if (this._scrollCounter < 10){
this._scrollCounter++;
}
else {
this._scrollCounter = 0;
// check position of empty placeholder div that stays relative
const placeholder = this.template.querySelector('div.placeholder');
this._startContainerPosition = this._findPositionY(placeholder);
}
const container = this.template.querySelector('div.container');
// if the scrollY is greater than the position, fixed the ad, otherwise leave it as relative
if (scrollY > this._startContainerPosition) {
container.style.minWidth = `${container.clientWidth}px`;
container.style.position = 'fixed';
container.style.zIndex = 10;
container.style.top = '20px';
} else {
container.style.position = 'relative';
}
}
}
As you can see, what I've done is made the y position update every 10th scroll rather than only on the initial scroll. (I had it on every scroll but that causes stuttering).
I've also added a "placeholder" div wrapper which is always relative, as checking the containers y position while it is fixed would also throw off the y value and cause undesirable behavior.
What I imagine to be the correct solution is the have a listener that can tell my component when the site changes and update the y value then and only the. Is this possible? Or is there an even bettersolution I'm missing?
I hope this all makes sense, Thanks, Andrew.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
