Section horizontal scroll with sticky
by sungsoonz
HTML
<section>
<p>Scroll</p>
</section>
<section id="first-sticky">
<p>Scroll</p>
</section>
<section>
<div class="container">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</section>
<section>
<p>Scroll</p>
</section>
<section class="sticky-parent">
<div class="sticky">
<div class="horizontal">
<div class="dim" style="background-color: aqua;"></div>
<div class="dim" style="background-color: rgb(255, 238, 0);"></div>
<div class="dim" style="background-color: rgb(81, 255, 0);"></div>
<div class="dim" style="background-color: rgb(247, 0, 255);"></div>
<div class="dim" style="background-color: rgb(27, 24, 179);"></div>
<div class="dim" style="background-color:black"></div>
</div>
</div>
</section>
<section></section>
CSS
html, body {
padding: 0;
margin: 0;
}
.sticky-parent {
height: 700vh;
}
.container {
padding: 6rem;
}
section {
width: 100vw;
height: 100vh;
position: relative;
background: #fff;
}
p {
font-size: 10em;
text-align: center;
}
#first-sticky {
background: coral;
}
.stick {
position: sticky;
top: 0;
}
.sticky {
position: sticky;
top: 0px;
min-height: 100vh;
overflow-x: hidden;
overflow-y: hidden;
}
.dim {
display: block;
min-width: 100vw;
height: 100vh;
}
.horizontal {
display: flex;
}
@media (max-width: 620px) {
.dim {
display: block;
min-width: 100vw;
height: 100vh;
}
}
JavaScript
document.addEventListener('scroll', horizontalScroll);
const sticky = document.querySelector('.sticky');
const stickyParent = document.querySelector('.sticky-parent');
let scrollWidth = sticky.scrollWidth;
let verticalScrollHeight = stickyParent.getBoundingClientRect().height - sticky.getBoundingClientRect().height;
//Scroll function
function horizontalScroll() {
//Checking whether the sticky element has entered into view or not
let stickyPosition = sticky.getBoundingClientRect().top;
if (stickyPosition > 1) {
return;
} else {
let scrolled = stickyParent.getBoundingClientRect().top; //how much is scrolled?
sticky.scrollLeft = (scrollWidth / verticalScrollHeight) * (-scrolled) * 0.85;
}
}