Web Development

Menu Drag and scroll in left and right using Mouse : HTML CSS and JavaScript

Basically I got the code from Codepan. But I am describing it here again with my html and css for the novice users. I am sharing the CSS, HTML and Javascript related to it.

CSS

<style>
.menu {
    overflow-x: scroll;
    display: -webkit-box !important;
    flex-wrap: inherit !important;
    width: 251px;
}
ul.menu li {
    list-style: none;
    margin-right: 12px;
}
</style>

HTML

<ul class="menu">
<li><a>test 1</a></li>
<li><a>test 2</a></li>
<li><a>test 3</a></li>
<li><a>test 4</a></li>
<li><a>test 5</a></li>
<li><a>test 6</a></li>
<li><a>test 7</a></li>
<li><a>test 8</a></li>
<li><a>test 9</a></li>
<li><a>test 10</a></li>

</ul>

Javascript

<script>

const slider = document.querySelector('ul.menu');
let isDown = false;
let startX;
let scrollLeft;

slider.addEventListener('mousedown', (e) => {
  isDown = true;
  slider.classList.add('active');
  startX = e.pageX - slider.offsetLeft;
  scrollLeft = slider.scrollLeft;
});
slider.addEventListener('mouseleave', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mouseup', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mousemove', (e) => {
  if(!isDown) return;
  e.preventDefault();
  const x = e.pageX - slider.offsetLeft;
  const walk = (x - startX) * 3; //scroll-fast
  slider.scrollLeft = scrollLeft - walk;
 // console.log(walk);
});

</script>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s