Experience the feeling of releasing momentum by click and dragging the scroll

One feature I am looking for is the ability to control the scroll speed when dragging, and have the scroll continue moving slightly after release instead of stopping instantly.

CodePen: https://codepen.io/rKaiser/pen/qGomdR

I can adjust the speed adequately, but I'm wondering if it's possible to add some momentum or if there is a better plugin that would suit this purpose. Thank you.

const slider = document.querySelector('.container');
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) * 0.3; //scroll-speed
  slider.scrollLeft = scrollLeft - walk;
});

Answer №1

To achieve a smooth scroll effect after releasing the mouse button, you can increment the scrollLeft property on every frame until the speed reaches 0. Here's an example of how you could implement this:

slider.addEventListener('mouseup', () => {
  isDown = false;
  slider.classList.remove('active');
  speed = (-scrollLeft+slider.scrollLeft)/(new Date()-t)*500; // t is the time when the mouse button was pressed

  const draw=()=>{
    if(speed>0){
      slider.scrollLeft = slider.scrollLeft + speed--; // increase scroll amount
    } else {
      momentum=false;
    }
    requestAnimationFrame(draw);
  }
    momentum=true;
    draw();
});

slider.addEventListener('mousemove', (e) => {
  if(!isDown && !momentum){
    return;
  }..

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to display and download a PDF file on a JSP web page

Can anyone help me with a simple trick to solve this question I have? In my project folder, I have 5 PDF files named file1.pdf, file2.pdf, file3.pdf, file4.pdf, and file5.pdf. I want to display these files in 5 rows on my webpage, each row containing VIEW ...

Using CSS to create a color combination of black with varying opacities

I attempted to achieve a black color by blending together the colors red, yellow, and blue in CSS, but encountered an issue... Is there a way to create black color using opacity? ...

Exploring the world of XD plugins, utilizing npm packages and Node.js APIs

Is it feasible to integrate npm packages and Node.js APIs into my Adobe XD plugin development process? ...

Cleaning up extra spacing following the implementation of the "top" tag in CSS

I've been working on a project for this site and I've encountered a small issue. Despite my efforts, I can't seem to resolve it :/ There's an unwanted whitespace at the bottom of my webpage, in the footer section. I've attempted ...

The font from the server is not displaying correctly in the local HTML file

After uploading the ttf font file to the server, I utilized the following CSS code: @font-face { font-family: "fontname"; src: url("http://www.mywebsite.com/Fonts/fontname.ttf"); } body { font-family: "fontname", sans-serif; } Within the loc ...

Incorporating HTML with ng-binds through transclusion

I have been developing an angular directive to enhance the functionality of ng-table by adding filtering and exporting features. The main goal is to make this directive reusable for multiple tables, which requires the <td> elements to be dynamic. To ...

A combination of various select menus along with conditional statements

I am dealing with a situation where I have two select menus that can modify the displayed data on the page. Currently, I have code in place that updates the data based on changes made to one of the select menus, and it is functioning properly. This funct ...

Introducing a new feature in React-Select: enabling copy-paste functionality for the multi-select text

Incorporating a react-select component (specifically generated using CreatableSelect) into my project has been quite beneficial. This multi select text input feature allows users to conveniently add keywords as options. While the current functionality is ...

The error callback for Ajax is triggered even though the JSON response is valid

Within my JavaScript file, I am making the following call: $.ajax({ type: "POST", dataType: "application/json", url: "php/parseFunctions.php", data: {data:queryObj}, success: function(response) { ...

Totally clueless when it comes to JSON

After diving into tutorials on JSON, the structure and syntax are finally clicking for me. However, I'm currently working on a project that requires a GET, and it seems like JSON could help with this. I've come across comparisons of JSON and AJA ...

Discovering the method for accessing a variable within jQuery from a regular JavaScript function

As someone new to jQuery, I am currently facing a challenge with accessing a variable defined inside a jQuery block from a regular function. Despite my attempts, I have been unsuccessful in accessing it. Can anyone guide me on how to do this? <script l ...

HTML/ModX styling for selected textboxes

I am looking to enhance the style of my search-box, which is similar to the one on THIS website. While I have tried using :active, the effect only lasts for a brief moment. Currently, my code is heavily influenced by modX terms, but I will still share it h ...

Enhancing data rendering by incorporating extra verifications through the logical AND operator to prevent crashes upon page refresh

Upon refreshing the page, my app crashed. The issue stemmed from the page loading faster than my data, prompting me to include additional checks using the logical AND operator. While effective in preventing crashes, this approach seems laborious and begs t ...

The icons from Font Awesome are not displaying properly in Angular version 15

I have been searching for new information to help solve the error I am experiencing but haven't found any useful results. Here is my issue: I am working on a project in Angular 15.1.0 and want to incorporate some Font Awesome icons. To do this, I foll ...

What could be causing the TypeError that is preventing my code from running smoothly?

I can't seem to figure out why I'm constantly encountering the error message Cannot destructure property 'id' of 'this.props.customer' as it is undefined.. Despite double-checking my code and making sure everything looks corre ...

jQuery - contrasting effects of the before() and after() functions

I'm working with a sortable list that is not using jQuery UI sortable, but instead allows sorting by clicking on buttons. Sorting to the right using after() works perfectly, however, sorting to the left with before() is causing issues. First, here&ap ...

When I upgraded my "react-router-dom" from version "5.2.0" to "6.14.0", I encountered a warning stating "No routes matched location"

After updating react-router-dom from version "5.2.0" to "6.14.0", I encountered a warning saying "No routes matched location." Initially, I received an error stating that "<Route> is only meant to be used as a child of <Routes>, not rendered d ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

Leveraging ng-model with expressions in ng-repeat in AngularJS.Would you

Currently, I am tasked with creating a form for a multilanguage content management system using angularJS. The language list has been defined within the angular scope as follows: $scope.languages = [ {id:0,'name':'English'}, {id:1, ...

Iterate over the HTML elements within a class and retrieve a specific property in JSON

Currently, I am in the process of developing a straightforward application that involves making an Ajax request to retrieve a Json object and then passing it to an HTML document. Essentially, this application functions as a vending machine where the produc ...