Methods for activating touch-like scrolling through the use of mouse grabbing and dragging

Let me show you a simple illustration of the task I'm attempting to accomplish:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    #box {
      background-color: red;
      width: 200px;
      height: 250px;
      overflow-x: hidden;
      overflow-y: scroll;
      cursor: grab;
    }
    #box div {
      background-color: blue;
      margin: 30px;
      width: 100px;
      height: 100px;
    }
  </style>
</head>
<body>
  <div id="box">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</body>
</html>

For those using a mobile device, navigating through #box is as simple as touching and swiping up or down. However, for desktop users, the scrolling process has to be done either by using the scrollbar or the mouse scroll wheel.

Is there a way to implement scrolling by grabbing (i.e. clicking and holding the left mouse button) and then dragging (i.e. moving the mouse) up or down? Can this issue be addressed using CSS alone?

Answer №1

Unfortunately, CSS alone cannot solve this issue, but using JavaScript can provide a solution. I have created a script that allows for both horizontal and vertical scrolling, with the ability to adjust the scroll speed.

const box = document.getElementById('box');

let isDown = false;
let startX;
let startY;
let scrollLeft;
let scrollTop;

box.addEventListener('mousedown', (e) => {
  isDown = true;
  startX = e.pageX - box.offsetLeft;
  startY = e.pageY - box.offsetTop;
  scrollLeft = box.scrollLeft;
  scrollTop = box.scrollTop;
  box.style.cursor = 'grabbing';
});

box.addEventListener('mouseleave', () => {
  isDown = false;
  box.style.cursor = 'grab';
});

box.addEventListener('mouseup', () => {
  isDown = false;
  box.style.cursor = 'grab';
});

document.addEventListener('mousemove', (e) => {
  if (!isDown) return;
  e.preventDefault();
  const x = e.pageX - box.offsetLeft;
  const y = e.pageY - box.offsetTop;
  const walkX = (x - startX) * 1; // Adjust scroll speed here
  const walkY = (y - startY) * 1; // Adjust scroll speed here
  box.scrollLeft = scrollLeft - walkX;
  box.scrollTop = scrollTop - walkY;
});
#box {
  background-color: red;
  width: 200px;
  height: 250px;
  overflow-x: hidden;
  overflow-y: scroll;
}
#box div {
  background-color: blue;
  margin: 30px;
  width: 100px;
  height: 100px;
}
<div id="box">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

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

Getting the nested object property with pluck using Lodash

I have an array of objects containing character information: var characters = [ { 'name': 'barney', 'age': 36, 'salary':{'amount': 10} }, { 'name': 'fred', 'age': ...

Node.js server only supports cross-origin requests for protocol schemes when working with an Angular front end

Struggling to configure CORS on a local site hosting a Node.js server and an Angular client. Encountering the following error: Access to XMLHttpRequest at 'localhost:3000/api/v1/users' from origin 'http://localhost:4200' has been bl ...

Issue with data-ng-class function not being invoked

I'm currently working on a simple Angular project where I need to dynamically color list items based on a function called in data-ng-class. Below is an excerpt from my HTML file: <div> Rooms:<ul style="list-style:none;"> < ...

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

The issue of overflowing scroll functionality appears to be malfunctioning

.main-content{ height: 100%; width: 60%; min-height: 800px; background-color: white; border-radius: 5px; margin-left: 1%; border: solid 1px black; } .profile-banner{ display: flex; flex-direction: row; justify-content: space-between; ...

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates – a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

Acquire a JSON response from a web address by utilizing JavaScript

If you navigate to , you will find a JSON file filled with information about your current geolocation. My goal is to save this JSON data into JavaScript variables, allowing me to manipulate and extract specific fields from the file. ...

"Triggering ngClick causes ngSrc to update, however, the keydown event handler does not have

Currently, I am developing a dynamic live map application that includes various navigation buttons like pan and zoom. To enable keyboard control, I have implemented a keydown event handler that triggers the same function as the button clicks. Interestingl ...

Create a unique Bitcoin address using a derivation scheme

Starting with a derivation scheme that begins with tpub... for the testnet, I am looking to generate bitcoin addresses from this scheme. I also need a method that will work for the mainnet. Is there a library available that can assist me with this task? ...

Styling a Form Submission with CSS

I am currently working on a website that contains the following PHP code: echo "<form action='choice.php' method='post'>"; echo "<input type='submit' name='choice' value='left' /> "; As I am i ...

retrieve the complete webpage content, encompassing the .html file, images, .js files, css stylesheets, and more

I'm currently working on a project and could use some assistance. Is there a method available to download an entire page, including the .html file, images, .js files, css, etc., using PHP, JavaScript, or AJAX? <html> <body> & ...

unable to modify the content within a div by clicking on a link

Lately, I've been experimenting with a code snippet I found on this fiddle: http://jsfiddle.net/unbornink/LUKGt/. The goal is to change the content of a div when clicking on links to see if it will work on my website. However, no matter which link I c ...

Executing a JavaScript function when a column in a Fusion Chart is clicked

I have two div elements in HTML and I would like to have div2 load when div1 is clicked. Additionally, whenever div2 loads, a back button should also appear to return to div1. Is there a way to achieve this using HTML? <td background="images/bgTd.gif ...

Similar to Jquery ajax, Titanium also offers a powerful tool

Currently, I have been making an API call using Titanium in the following way: var url = "http://www.appcelerator.com"; var client = Ti.Network.createHTTPClient({ // callback when data is received onload : function(e) { Ti.API.info("Re ...

Hide the popup menu when the user clicks outside of it

I am presenting the following code <!DOCTYPE html> <html> <head> <title>GalacticCraft</title> <link rel="stylesheet" type="text/css" href="style.css" /> <link rel="shortcut icon" type="image/png" href="fa ...

What could be causing the removal of style classes from my element after it is appended?

Could you please explain how it functions? I am attempting to append a div with content using innerHTML and it is working, but without any of the styling classes being applied. const element = document.createElement("div"); element.classList.add("col ...

List out IP addresses in JavaScript

Is it possible to allow users to input a range of IP addresses in a specific format? 10.5.15.[22-25],10.5.16.[35-37],10.5.17.20 The desired outcome is to return an array of these IP addresses for connection checking purposes later on. 10.5.15.22 10.5.15 ...

Enforce a restriction on the user's input value for the amount field within a React application

I'm looking to limit the user from entering more than 50000 in the input value. How can I achieve this using React? I am currently handling this on the onchange event. onPaymentAmountChanged = (e) => { let inputValue = e.target.value; if (i ...

Event trigger malfunction or potential issue with index activation

.full-arrow is a unique arrow that allows selection of the next page. The .full-navigation serves as a navigation bar, consisting of boxes in a line that change color upon selection. Although the full function may not be displayed here, you can grasp the b ...

My custom styles no longer seem to be applying after upgrading Angular Material from version 14 to 15. What could be causing this issue

Having some challenges with the migration from Angular 14 to Angular 15 when it comes to overriding material UI elements and themes. Looking for blog posts or documentation that can provide guidance on how to smoothly transition. Specifically, experiencin ...