I have a simple code using the IntersectionObserver, that basically tells when an object is visible on the screen, when that happens I want a title to change to the same name of that visible element. The thing is that I've created 5 different variables for each observer related to each of the 5 upcoming areas. Is there a way to simplify this code?
Right now it works but seems to be wrong to me and I cannot figure out how to merge them all.
Thanks in advance!!
var observer = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true)
document.querySelector(".productTitle").innerHTML = "Logotype";
}, { threshold: [1] });
var observer1 = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true)
document.querySelector(".productTitle").innerHTML = "Branding";
}, { threshold: [1] });
var observer2 = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true)
document.querySelector(".productTitle").innerHTML = "Website Dev.";
}, { threshold: [1] });
var observer3 = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true)
document.querySelector(".productTitle").innerHTML = "3d Modeling";
}, { threshold: [1] });
var observer4 = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true)
document.querySelector(".productTitle").innerHTML = "Vectorial Work";
}, { threshold: [1] });
observer.observe(document.querySelector("#visibleLogo"));
observer1.observe(document.querySelector("#visibleBranding"));
observer2.observe(document.querySelector("#visibleWeb"));
observer3.observe(document.querySelector("#visible3d"));
observer4.observe(document.querySelector("#visibleVector"));
.page to your articles Elements.page inside a.forEach().data-* attribute to store the desired title in the HTML itself like i.e: data-title="Title to show when in viewport"const elTitle = document.querySelector(".productTitle");
const pageInViewport = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
elTitle.textContent = entry.target.dataset.title;
}
});
};
const pageObs = new IntersectionObserver(pageInViewport);
const obsOptions = {threshold: [1]};
// Attach observer to every .page element:
document.querySelectorAll('.page')
.forEach(EL => pageObs.observe(EL, obsOptions));
* {
margin: 0;
box-sizing: border-box;
}
.productTitle {
position: fixed;
top: 0;
background: gold;
}
.page {
padding: 30px;
border: 1px solid #000;
height: 100vh;
}
<div class="productTitle"></div>
<div class="page" id="visibleLogo" data-title="Logotype">visibleLogo</div>
<div class="page" id="visibleBranding" data-title="Branding">visibleBranding</div>
<div class="page" id="visibleWeb" data-title="Website Dev.">visibleWeb</div>
<div class="page" id="visible3d" data-title="3d Modeling">visible3d</div>
<div class="page" id="visibleVector" data-title="Vectorial Work">visibleVector</div>