Instructions on how to create a horizontal scrolling div using the mouse scroll wheel

I need help with scrolling a div horizontally using the mouse scroll button. My div does not have a vertical scroll and I would like users to be able to scroll horizontally. Can anyone provide guidance on how to achieve this?

Answer №1

<html>
  <head>
    <title>Scrolling Test</title>
    <script type='text/javascript'>
      window.onload = function(e) {
        evt = e || window.event;

        var mousewheelevt=(/Firefox/i.test(navigator.userAgent)) ? 'DOMMouseScroll' : 'mousewheel';

        if(document.attachEvent) {
          document.getElementById('scrollableDiv').attachEvent('on'+mousewheelevt, scroll);
        } else {
          document.getElementById('scrollableDiv').addEventListener(mousewheelevt, scroll, false);
        }
      }


      function scroll(evt) {
        scrollTarget = evt.currentTarget || evt.srcElement;

        if(scrollTarget.scrollWidth > scrollTarget.offsetWidth) {
          var delta = Math.max(-1, Math.min(1, (evt.wheelDelta || -evt.detail)));
          switch(delta) {
            case 1:
              scrollTarget.scrollLeft -= 32;
              break;

            case -1:
              scrollTarget.scrollLeft += 32;
              break;
          }
        }
      }

    </script>
  </head>


  <body>


    <div id='scrollableArea' style='width: 256px; height: 256px; position: absolute; overflow: hidden;'>
      <div style='width: 400px;'>
Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test Sample text for scrolling test
      </div>
    </div>


  </body>
</html>

Answer №2

Typically, this task involves leveraging JavaScript. While I'm unable to supply the exact code at this time, the concept is fairly straightforward:

  1. When the user hovers over an element
  2. Attach a scroll event handler
  3. Upon a scroll event triggering, calculate the precise amount that was scrolled (in pixels) and either halt the event or navigate back up to the initial position.
  4. Utilize CSS properties like margin-left on the element, adjusting it in line with how much the user has scrolled vertically.
  5. (Optionally) Confirm if the element's right edge has been reached; if so, prevent further scrolling to avoid it disappearing off the page's left side.

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

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

Diminishing sheets in the realm of C# web application development

I have been researching ways to incorporate a fading page function, but I am encountering some issues. I am unsure about the specific code that needs to be included in jquery.js and how to integrate this script into all of my web forms or alternatively int ...

In Javascript, you can throw, instantiate a new Error(), and populate its custom properties all in a single line of code

Can all of this be done in a single line? if (!user) { const error = new Error('Invalid user.') error.data = someObject error.code = 401 throw error } Here's an example (with data and code properties populated) if (!user) th ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...

Enhance the appearance of your Table footer with a personalized touch

I have two different Text components that I am working with. You can view some examples of these components here. Here is the scenario: Text1 is located within a form (labeled as text) Text2 is situated in the footer area of a table In each text, I hav ...

Having trouble with the tool tip not showing up correctly in Internet Explorer?

Check out the code snippet below: <table> <tr> <td class="bgimg" valign="middle" width="10%" title="some title" nowrap> <img src="images/SomeLogo.gif"/> </td> </tr> </table ...

Obtain the identification number and full name from the typeahead feature

I am able to retrieve the name and ID, but I am only able to display the name. I have attempted using update and afterslected methods. Currently, I have this code which works well, however, it only fetches the name! $('input.typeahead').typea ...

What is the method for embedding HTML content into the header section of tcpdf?

I am currently utilizing the tcpdf library to create a PDF document. I have implemented the smarty template engine to manage the data. Below is the code snippet for inserting header data: // set default header data $pdf->SetHeaderData(PDF_HEADER_LOGO, ...

Incorporating custom CSS and HTML into the link is essential for enhancing the appearance of KnpMenu

I'm working with the KnpMenuBundle and I need to customize a link that has the route 'uri'=>'#'. How can I achieve this? The desired link should be styled like this: <a href="#" class="js-sub-menu-toggle"> <s ...

Find the total sum of various spans

As a beginner in programming, I am facing a challenge that I cannot seem to solve. How can I retrieve the values of multiple spans with the same class? This is how the HTML code looks: <ul> <li> <input type="checkbox" value="30 ...

Executing password validation on login/register form using Node.js and EJS

In order to demonstrate a simple login page, I have created a form that requests typical information like username, password, etc. Additionally, it prompts the user to confirm their password, and if the lengths do not match, an error is triggered to notify ...

Create beautiful PDF documents using the KNP Snappy Bundle, seamlessly converting dynamically modified Twig templates

Currently, I am attempting to create a PDF from a tweaked Twig on the client side. My approach involves sending the modified HTML document to the server via AJAX. However, this method is proving ineffective as the server is returning a binary document that ...

Is Immutable state considered a key functional aspect in the ReactJs framework?

One key aspect of an imperative program is the emphasis on state and its modifications. When it comes to ReactJs, there is a push for more functional programming styles, such as using purity and higher-order functions. I'm curious to explore whether ...

Encountering errors while attempting to share files in a system built with Node.js, Express,

This snippet shows my Node.js code for connecting to a database using Mongoose const mongoose = require('mongoose'); function connectDB() { // Establishing Database connection mongoose.connect(process see your Naughty's you're sure ...

Is there a way to verify the existence of a specific error in the console?

There seems to be a conflict between a WordPress plugin or code left behind by the previous programmer, causing the WordPress admin bar to always remain visible. While no error is triggered for admins, visitors may encounter a console error. My goal is to ...

Can you explain the contrast between open and closed shadow DOM encapsulation modes?

My goal is to create a shadow DOM for an element in order to display elements for a Chrome extension without being affected by the page's styles. After discovering that Element.createShadowRoot was deprecated, I turned to Element.attachShadow. Howeve ...

How can I use AJAX to read an image file and display it on a Canvas?

Is there a way to read an image from my server using Ajax and then display it on Canvas? I am aware that this can be achieved by using normal image tags and canvas draw methods, as shown below: <img id="myImage" src="./ColorTable.PNG" style="display:n ...

The relationship between two distinct servers: Express.js and Node.js

Working with the Express.js framework and Node.js, I am trying to make a request to an MS SQL database on the server side. My goal is to retrieve data (in JSON or array format) from the server and send it to the client side. I'm unsure about how to ...

The JSON.stringify method may not accurately reflect the original object that was converted into a string

Working on a Connect Four app for my school project has been an interesting challenge. At the moment, I am grappling with JSON.stringify and trying to encode an object that holds a two-dimensional array of "hole" objects to eventually send it to the server ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...