I forbindelse med kurset Kommunikasjonsdesign utviklet vi en JavaScript-kode som bytter et bakgrunnsbilde på en Parallax-seksjon ettersom nye tekst-blokker scrolles inn i viewport i nettleseren. Her er koden for dette.
HTML
<section id="changesSection" class="scrollContainer scrollContainerDynamicBG">
<div id="loser" class="scrollText">
<h2>The first section to change background image</h2>
<p>Changes to bilde1.jpg</p>
</div>
<div id="winner" class="scrollText">
<h2>The second section to change background image</h2>
<p>Changes to bilde2.jpg</p>
</div>
<div id="conclusion" class="scrollText">
<h2>The third section to change background image</h2>
<p>Changes to bilde3.jpg</p>
</div>
</section>
Code language: HTML, XML (xml)
CSS
.scrollContainer {
width: 100%;
min-height: 100vh;
position: relative;
overflow: hidden;
padding-bottom: 20vh;
}
.scrollContainerDynamicBG {
transition: background-image 2s;
background-size: cover;
background-attachment: fixed;
background-repeat: no-repeat;
background-position: center center;
}
.scrollText {
max-width: 50rem;
padding: 2rem;
background: #fff;
color: #232323;
font-family: 'Fira Sans', sans-serif;
margin: 30rem auto;
}
.textBlock {
max-width: 50rem;
margin: 0 auto;
}
Code language: CSS (css)
JavaScript
//FUNCTION TO CHECK IF ELEMENT IS IN VIEWPORT
function isInViewport(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 && rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
//EVENTLISTENER TO CONTROL CHANGES
document.addEventListener('scroll', function () {
if(isInViewport(document.getElementById("loser"))) {
document.getElementById("changesSection").style.backgroundImage = "url(bilde1.jpg)"
}
if(isInViewport(document.getElementById("winner"))) {
document.getElementById("changesSection").style.backgroundImage = "url(bilde2.jpg)"
}
if(isInViewport(document.getElementById("conclusion"))) {
document.getElementById("changesSection").style.backgroundImage = "url(bilde3.jpg)"
}
}, {
passive: true
});
Code language: JavaScript (javascript)