Issue
I'm aiming to recreate an animation using JavaScript and CSS. It involves a list of words from a CMS, where the quantity of a single word can change. The goal is to create an endless vertical scrolling effect without a visible loop restart, similar to a marquee. I'm struggling with modifying my code to achieve the desired behavior. CSS animations are a bit challenging for me to grasp, so any assistance would be greatly appreciated. I'm open for a new markup structure if necessary.
My code: https://codesandbox.io/s/2v85nk?file=/src/TextSlider.js
The desired effect: https://drive.google.com/file/d/1bDVqeulKpwFyDKA9sKqxduR7OFgBZKK0/view?usp=sharing
I attempted to modify these two lines within .slider-item, making some progress but not quite reaching the desired outcome.
.slider-item {
opacity: 0.5; // Added to show the previous item slightly while transitioning
transform: translateY(-100%); // Altered scrolling direction
}
Solution
We can use scroll snapping. Explanation in comments.
// give nudge to trigger scroll snap
function flick(e) {
// scroll back up if reached end
if (e.scrollHeight - e.scrollTop - e.clientHeight < 1) {
e.scrollTop = 0;
}
e.scroll({
top: e.scrollTop + 51,
behavior: "smooth"
});
}
window.addEventListener("load", () => {
const slider = document.querySelector(".slider");
setInterval(flick, 2000, slider);
});
.slider {
height: 100px;
width: 200px;
overflow: hidden;
scroll-snap-type: y mandatory;
}
.item {
height: 100px;
font-size: 2rem;
font-weight: bolder;
display: flex;
scroll-snap-align: center;
}
/* cosmetics */
.item * {
margin: auto;
}
.item:nth-child(2n) {
background-color: skyblue;
}
.item:nth-child(2n + 1) {
background-color: lime;
}
<div class="slider">
<div class="item"><span>1</span></div>
<div class="item"><span>2</span></div>
<div class="item"><span>3</span></div>
<div class="item"><span>4</span></div>
<div class="item"><span>5</span></div>
<div class="item"><span>6</span></div>
<div class="item"><span>7</span></div>
<div class="item"><span>8</span></div>
<div class="item"><span>9</span></div>
<div class="item"><span>1</span></div>
</div>
Answered By - the Hutt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.