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!

--

--

--

https://www.linkedin.com/in/itskushagra

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Strings, In a list group 2 consecutive characters.

How to deploy your serverless React App to Heroku

Don’t Create React Navbars Like I Once Did!

Build A Simple App with JavaScript Object Literal Pattern

HIGHER ORDER COMPONENTS (HOCs) IN REACT

Easily Parse JSON With The Powerful Jackson ObjectMapper

A Beginner’s Guide to ERROR Handling in JavaScript

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
Kushagra Kesav

Kushagra Kesav

https://www.linkedin.com/in/itskushagra

More from Medium

Day03 of #100DaysOfCode

CREATING THE GAME OF X AND O

My JavaScript Journey

The Beginner’s Guide to SASS