I want a scroll bar that is able to automatically scroll as well as having two buttons that be manually clicked to scroll right / left.
Problem:
-
Manual scroll Buttons are not working but the automatic scroll is, They are using the exact same code to scroll: “adverts.scrollBy({ left: 20, behavior: ‘smooth’ });”
-
Even after i remove the automatic scroll code the manual scroll buttons do not work.
What i need help with:
Having Manual scroll buttons and Automatic scroll working at the same time.
HTML Code:
<div class="scrollbar">
<div class="adverts">
<a href="" class="advert w">
<div class="img"></div>
</a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
<a href="" class="advert w"></a>
<a href="" class="advert b"></a>
</div>
</div>
<div class="scroll right" onclick="scrollLeft">right</div>
<div class="scroll left" onclick="scrollRight">left</div>
<script>
const adverts = document.querySelector('.adverts');
//Manual Scroll
function scrollRight() {
adverts.scrollLeft -= 100;
}
function scrollLeft() {
adverts.scrollBy({ left: 100, behavior: 'smooth' });
}
// Automatic Scroll (Wait 3 seconds before start)
setTimeout(() => {
setInterval(() => {
adverts.scrollBy({ left: 20, behavior: 'smooth' });
}, 10);
}, 3000);
var text = 0;
</script>
CSS Code
.scrollbar {
margin-top: 50px;
}
.scroll {
width: 50px;
height: 50px;
outline: 1px solid black;
cursor: pointer;
}
.adverts {
/*position: absolute;*/
white-space: nowrap;
overflow: auto;
width: 100%;
height: 300px;
background: grey;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 10px;
scrollbar-width: none;
text-align: center;
}
.advert {
margin-left: 10px;
display: inline-block;
width: 250px;
height: 100%;
background-color: white;
}
.advert .img {
width: 90%;
margin: 5%;
height: 60%;
outline: black 3px solid;
}