Day27 of #100DaysOfCode

#CodeTogether Day 27/100

Hii folks 🙌

Today I have completed the 27th video of JavaScript30!

Project 27: Click and Drag to Scroll

Source: https://javascript30.com

Learnings:

So, today we have been tasked to make a neat horizontal scroll click and drag accordion or carousel.

There will be a number of event listeners in use to achieve this. mousedown, mouseleave, mouseup, and mousemove. We kept a boolean that keeps track of whether the mouse is down or up, and we set the Element.scrollLeft property to the number of pixels the user dragged the element.

Now, we start setting up several variables.

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

Next, we added event listeners with functions. mousedown activated the slider.

slider.addEventListener('mousedown', (e) => {
isDown = true;
slider.classList.add('active');
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
});

mouseLeave & mouseup turned the slider off.

slider.addEventListener('mouseleave', () => {
isDown = false;
slider.classList.remove('active');
});
slider.addEventListener('mouseup', () => {
isDown = false;
slider.classList.remove('active');
});

And, the mousemove made the slider scroll leftward.

slider.addEventListener('mousemove', (e) => {
if (!isDown) return; // stop the fn from running
e.preventDefault();
const x = e.pageX - slider.offsetLeft;
const walk = (x - startX) * 3;
slider.scrollLeft = scrollLeft - walk;
});

The program resulted in a nice effect as you moved the mouse horizontally to scroll, click and drag the carousel.

The Carousel

Today I Learned (T-I-L):

That is all for Day27 ✅

Thanks for reading, See you tomorrow!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store