I have been working on structuring a blog post layout that involves having metadata fixed on one side while the content scrolls. I am utilizing position: sticky
to achieve this effect.
The setup works well, but some types of content extend to 100% width, which causes them to overlap with the metadata as they scroll past. To address this issue, I am trying to implement an event listener that tracks the position of both elements and adds a class to the sticky element, setting its opacity to 0
when the other element passes over it.
The current solution functions properly when there is only one full-width (.fw
) element on the page:
window.addEventListener('scroll', function() {
var a = document.querySelector('.postmeta-sticky').getBoundingClientRect(),
b = document.querySelector('.fw').getBoundingClientRect();
if((b.top <= (a.top + a.height)) && ((b.top + b.height) > a.top)) {
$(".postmeta-wrap").addClass("overlap");
} else {
$(".postmeta-wrap").removeClass("overlap");
}
});
However, because the post content gets generated dynamically, there could be multiple instances of .fw
per page. Therefore, I am attempting to gather all instances using querySelectorAll
for my second variable, but I seem to be running into issues making this work.
This is how far I've gotten:
window.addEventListener('scroll', function(){
var a = document.querySelector(".postmeta-sticky").getBoundingClientRect(),
objects = document.querySelectorAll(".fw");
objects.forEach(function(object) {
b = object.getBoundingClientRect();
if ((b.top <= (a.top + a.height)) && ((b.top + b.height) > a.top)) {
$(".postmeta-wrap").addClass("overlap");
} else {
$(".postmeta-wrap").removeClass("overlap");
}
});
});
Unfortunately, the code isn't functioning as expected. There must be some mistake or missing piece in my implementation.
Here are the links to see the issue in action and the simplified CodePen:
First instance only working in situ:
Simplified CodePen: https://codepen.io/MMS_/pen/VwQvvpm
Any assistance provided is highly appreciated.
jQuery(document).ready(function($) {
window.addEventListener('scroll', function() {
var a = document.querySelector(".sticky-content").getBoundingClientRect(),
objects = document.querySelectorAll(".fw");
objects.forEach(function(object) {
b = object.getBoundingClientRect();
if ((b.top <= (a.top + a.height)) && ((b.top + b.height) > a.top)) {
$(".sticky-wrap").addClass("overlap");
} else {
$(".sticky-wrap").removeClass("overlap");
}
});
});
});