I am trying to create a generic component to stick the header in LWC.
Here is my component.
HTML
<template>
<div id="stickyId" class="myStickyHeader">
<slot>
<!-- Sticky content goes here -->
</slot>
</div>
</template>
I have defined sticky2
to class for a sticky header.
Js controller
/* eslint-disable no-console */
import { LightningElement } from 'lwc';
export default class Sticky extends LightningElement {
renderedCallback() {
try {
window.onscroll = () => {
let stickysection = this.template.querySelector('.myStickyHeader');
let sticky2 = stickysection.offsetTop;
console.log('stickysection => ' + stickysection);
console.log('stickysection id => ' + stickysection.id);
console.log('sticky2 => ' + sticky2);
console.log('window.pageYOffset => ' + window.pageYOffset);
if (window.pageYOffset > sticky2) {
stickysection.classList.add("sticky2");
} else {
stickysection.classList.remove("sticky2");
}
}
} catch (error) {
console.log('error =>', error);
}
}
}
I am using this component in another component like.
<c-sticky>
<div> my header section </div>
</c-sticky>
This works well if I have only one instance of sticky
component on my lightning page with tabs. But when there are multiple instances, it is not applying the sticky2 class on the currenly focused header.
See the image below, I am want to stick the header section of the component in each tab. So when I am in the Details tab, its actully applying sticky2
class to header in Design tab.
I think there are two problems here.
- Onscroll method is not able to detect which component is currently focused.
- Tried querySelectorAll to get all of the 'divs' on the page. But could not get them.