Implement a horizontal scrollbar using jQuery

My div contains a horizontal scroll, but its width is smaller than the content inside.

This layout was achieved using CSS

div {
  width: 300px;
  overflow: auto;
}

div p {
  width: 600px;
}

Here is the HTML code:

<div>
  <p>
  This paragraph contains a very long text that extends beyond the width of the div.
  </p>
</div>

I would like to add a scroll listener so that when scrolling down with the mouse, the content moves to the right, and when scrolling up, it moves to the left.

var lastScrollTop = 0;

$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // code for scrolling down
   } else {
      // code for scrolling up
   }
   lastScrollTop = st;
});

It seems that $(window).scroll is not triggering.

I have prepared a jsfiddle here: https://jsfiddle.net/t8Lc4pjs/

How can I make sure that the event fires and how can I adjust the scroll movement based on the direction of the mouse scroll?

Answer №1

To detect mousewheel scrolling, use the mousewheel event. See an example here: https://jsfiddle.net/t8Lc4pjs/2/

jQuery

$(document).ready(function(){
var i=0;
     $(document).on('mousewheel', function(e){
    if(e.originalEvent.wheelDelta /120 < 0) {
   console.log('down');
   $('.scl').scrollLeft(i++);
    }
    else{
     console.log('up');
     $('.scl').scrollLeft(i--);
    }

    });
});

Note: To increase scroll speed, adjust the value of 'i' incrementally.

UPDATE

I have added code to prevent 'i' from exceeding the div width or going below 0, and also made the scroll faster. Check it out here: https://jsfiddle.net/t8Lc4pjs/3/

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 best way to make changes to the DOM when the state undergoes a

I've programmed the box container to adjust dynamically based on input changes. For instance, if I entered 1, it will generate one box. However, if I modify the input to 2, it mistakenly creates 3 boxes instead of just 2. import React from 'rea ...

Is it possible to customize the border spacing for individual cells?

My table resembles the one shown in this example I am looking to eliminate the gap between each "Previous" and "Current" cell pairs while still maintaining spacing between rows and other columns. Is there a way to achieve this? ...

Issue with the <mat-chip> component in Angular Material Design

One issue I am facing is with a mat-chip list. When I close the first item it works fine, but when I close the last item, all chips are closed. https://i.sstatic.net/opj7f.png Here is the HTML code snippet: <mat-form-field> <mat-chip-list #ch ...

The concept of Ajax and checkbox arrays

I recently started working with Ajax and tried following a tutorial from this source However, I encountered some issues while trying to make it work. Can someone please assist me with this? Below is the HTML code that I am using: <html> <head ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

Sending a substantial amount of HTML via $ajax does not seem to be functioning properly

Creating a product page for an e-commerce platform involves submitting data through an AJAX call to store it in the database. However, there is an issue when large amounts of HTML data are being passed, resulting in nothing being stored in the description ...

Using YQL and jQuery to parse an XML feed fails to function properly in Internet Explorer versions 10 and 11

I am utilizing YQL to extract data from a news feed that is hosted on a different domain. My script is designed to iterate through the items in the feed like this: getFeed(); function getFeed() { $.ajax({ url: "https://query.yahooapis.com/v1/publi ...

The button's color cannot be modified due to a malfunctioning event script that is not

Seeking an explanation for why my current implementation isn't working. I'm attempting to create a quiz with a multiple choice section where the correct answer turns green when clicked, and incorrect answers turn red. Despite validating the code ...

Divergent display of WordPress form input CSS between Firefox and Chrome

Trying to create an email opt-in box using Wordpress with a pre-installed theme. The box appears correctly in Firefox but is displaying incorrectly in Chrome. Issues include no padding in the text fields, different font colors, and extra padding above and ...

Calculate the number of rows in a table that contain identical values

I have a puzzling issue that has been on my mind. I currently have an SQL statement that selects specific rows from my database and displays them in an HTML table, which is functioning properly. However, I now need to determine how many rows have the same ...

I am struggling to increase the width of my input bar and center-align it

Below is the CSS class I've created to ensure that all elements remain centered on the user's screen. container: { display: "flex", position: "absolute", top: 0, left: 0, height: "100%&qu ...

Fill the image with width using Mat

While working on creating cards using Angular Materials, I encountered an issue where the image was not filling up the space as desired. The red area in the image indicates where I want the image to take up space. https://i.sstatic.net/vcc9U.png HTML: & ...

What is the best way to emphasize specific months and years in an Angular Material datepicker?

I have an array of days, which can be from any year. I am attempting to customize the Angular Material datepicker to highlight specific months and years in the selection views based on the array of days. .html <input [matDatepicker]="picker" ...

What steps do I need to take to convert this code from UI Router to the core ngRoute?

After purchasing a template from wrapbootrap, I encountered an issue with the code provided. The theme used the UI Route plugin, which allowed for states, views, and nested views, but unfortunately, it was not compatible with the ADAL Authentication librar ...

Combining multiple AngularJS expressions to form a URL within an interpolation statement

While this explanation may be lengthy, I appreciate your patience as I try to articulate the issue at hand. The error I'm currently encountering is as follows: Error: [$interpolate:noconcat] Error while interpolating: Strict Contextual Escaping disa ...

Error: When trying to access the 'details' property of an undefined element within a foreach loop in Vue.js, a TypeError occurs

While working in a foreach loop, I'm attempting to assign a value using this particular operator. $.each(this.form.details,(key,value)=>{ $.each(this.form.details,(key1,value1)=>{ this.form.details[key].total=76776; }); }); form: ...

jQuery and ajax not functioning properly for Codeigniter validation

I am currently having issues validating my form using CodeIgniter validation through jquery ajax. I can't seem to figure out where I might be going wrong. Can someone please guide me on how to properly implement CodeIgniter validation with jquery ajax ...

What is the designated destination for JWT Tokens?

For my user login/signup process, I'm utilizing JWT and have a query regarding how the token is transmitted. At present, I am saving the token as a property in a JSON object on the server side, then passing it to the front-end. Upon receiving the obj ...

Use Javascript to set cookies and remember the show state when clicked

Can you offer some advice? I am looking to add cookies to my simple JavaScript code. Currently, the div is displayed when clicking on a link, but it hides again when the page reloads. I would like to implement cookies to remember the show state for 7 days. ...

What could be causing my Font Awesome icon background to fail to load?

As a newcomer to website design, I am currently learning CSS. I seem to be facing an issue where the background for the first two icons has loaded successfully, but the second one isn't displaying. .bg-instagram { padding: 7px 10px; border-radi ...