Horizontal Scroll-menu
by scurrilus
HTML
<link rel="stylesheet" href="https://sf-uatnew.morgenpost.de/static/2022-10-24T11:36:54-4ab4cac/bmo/main.css">
<div class='wrapper navigation-right overflow-hidden'>
<nav class="w-full overflow-x-auto">
<ul class="flex">
<li>Abo</li>
<li>Sport</li>
<li>Politik</li>
<li>Wirtschaft</li>
<li>Verschiedenes</li>
<li>Region</li>
<li>Lokales</li>
<li>Fussball</li>
<li>Irgendwas</li>
<li>Panorama</li>
<li>Abo</li>
<li>Sport</li>
<li>Politik</li>
<li>Wirtschaft</li>
<li>Verschiedenes</li>
<li>Region</li>
<li>Lokales</li>
<li>Fussball</li>
<li>Irgendwas</li>
<li>Panorama</li>
</ul>
</nav>
<button>
>
</button>
</div>
CSS
button {
position: absolute;
right: 30px;
top: 0;
background: #333;
color: #fff;
width: 20px;
height: 20px;
}
li {
margin: 8px;
background: #ccc;
border: 2px solid transparent
}
/* Hide scrollbar for Chrome, Safari and Opera */
nav::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
nav{
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
.navigation-left,
.navigation-right {
position: relative;
text-align: center;
}
.navigation-left:before,
.navigation-right:after {
display: list-item;
background: #cc0000;
width: 20px;
height: 100%;
position: absolute;
top: 0;
}
.navigation-left:before {
content: 'l';
}
.navigation-right:after {
content: 'r';
right: 0;
}
JavaScript
const wrapper = document.querySelector('.wrapper')
const button = document.querySelector('button')
const nav = document.querySelector('nav')
const scrollBar = document.querySelector('ul')
const scrollBarWidth = scrollBar.scrollWidth
const scrollBarRealWidth = scrollBar.clientWidth
let scrollBarClientRect = scrollBar.getBoundingClientRect()
let calc = (scrollBarClientRect.left - scrollBarRealWidth) * -1
let scrollBack = false
const changeButton = (change) => {
scrollBack = change
button.innerText = change ? '<' : '>'
}
const changeListener = () => {
scrollBarClientRect = scrollBar.getBoundingClientRect()
calc = !scrollBack ? (scrollBarClientRect.left - scrollBarRealWidth) * -1 : nav.scrollLeft - scrollBarRealWidth
console.log('---', calc, scrollBarWidth, nav.scrollLeft)
if (calc === scrollBarWidth) {
changeButton(true)
wrapper.classList.remove('navigation-right')
}
if (calc < scrollBarWidth) {
wrapper.classList.add('navigation-right')
}
if (nav.scrollLeft === 0) {
changeButton(false)
wrapper.classList.remove('navigation-left')
}
if (nav.scrollLeft > 0) {
wrapper.classList.add('navigation-left')
}
}
button.addEventListener('click', (e) => {
changeListener()
nav.scroll({
left: calc,
behavior: 'smooth'
})
})
nav.addEventListener('scroll', (e) => {
changeListener()
})