I have a simple code that automatically scrolls paragraphs horizontally. This may get look like is "Breaking News" on some portals.
Now my Javascript script will automatically scroll but when he get on end scrolling will end.
I tried the option when it gets on the end fastly scroll on being but this was not the smooth option.
Is there any option how I can smoothly looping these scrolling paragraphs?
const flavoursContainer = document.getElementById('flavoursContainer');
const flavoursScrollWidth = flavoursContainer.scrollWidth;
window.addEventListener('load', () => {
self.setInterval(() => {
if (flavoursContainer.scrollLeft !== flavoursScrollWidth) {
flavoursContainer.scrollTo(flavoursContainer.scrollLeft + 1, 0);
}
}, 15);
});
.container {
width: 100vw;
overflow-x: scroll;
white-space: nowrap;
background-color: #fff;
display: flex;
-ms-overflow-style: none;
scrollbar-width: none;
}
.scroll-disabler {
width: 100vw;
height: 34.4px;
position: absolute;
background-color: rgba(0,0,0 , 0.0001);
}
::-webkit-scrollbar {
display: none;
}
p {
padding: 8px;
}
<div class="container" id="flavoursContainer">
<div class="scroll-disabler"></div>
<p>Vyskúšajte Vyskúšajte Vyskúšajtee Vyskúšajte Vyskúšajte Vyskúšajtee Vyskúšajte Vyskúšajte Vyskúšajtee</p>
<p>Vyskúšajte Vyskúšajte Vyskúšajte Vyskúšajte Vyskúšajte Vyskúšajte Vyskúšajte Vyskúšajte Vyskúšajte</p>
</div>
This is how I would do it:
isElementInViewport(el)
which will return false when an element has scrolled outside of vision.You can see a working snippet below:
const flavoursContainer = document.getElementById('flavoursContainer');
const flavoursScrollWidth = flavoursContainer.scrollWidth;
window.addEventListener('load', () => {
self.setInterval(() => {
const first = document.querySelector('#flavoursContainer p');
if(!isElementInViewport(first)){
flavoursContainer.appendChild(first);
flavoursContainer.scrollTo(flavoursContainer.scrollLeft - first.offsetWidth, 0);
}
if (flavoursContainer.scrollLeft !== flavoursScrollWidth) {
flavoursContainer.scrollTo(flavoursContainer.scrollLeft + 1, 0);
}
}, 15);
});
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return rect.right > 0;
}
.container {
width: 100vw;
overflow-x: scroll;
white-space: nowrap;
background-color: #fff;
display: flex;
-ms-overflow-style: none;
scrollbar-width: none;
}
.scroll-disabler {
width: 100vw;
height: 34.4px;
position: absolute;
background-color: rgba(0,0,0 , 0.0001);
}
::-webkit-scrollbar {
display: none;
}
p {
padding: 8px;
}
<div class="container" id="flavoursContainer">
<div class="scroll-disabler"></div>
<p>This is the first News: big news</p>
<p>This is the second News: big news</p>
<p>This is the third News: big news</p>
<p>This is the fourth News: big news</p>
<p>This is the fifth News: big news</p>
<p>This is the last News: big news</p>
</div>