简体   繁体   中英

Create an horizontal scroll in jQuery

I have an horizontal scroll in a div which has small width than its children width.

I made it possible with CSS

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

div p {
  width: 600px;
}

and HTML:

<div>
  <p>
  this is very looooooooooong text and very loooonggg paragraph
  </p>
</div>

I want to add scroll listener when I scroll down (from mouse) then scroll that div's content to right, if scroll up then scroll div's content to left.

var lastScrollTop = 0;

$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st;
});

seems that $(window).scroll doesn't fire.

I created jsfiddle: https://jsfiddle.net/t8Lc4pjs/

How to fire that event and how to move scroll to left/right depends on the direction of mouse scroll ?

Use mousewheel event to detect the mousewheel scroll.. kindly check 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: If you want to scroll bit faster increment the value of `i' bit more

UPDATE

I have added code to stop value of i exceeding width of the div and going below 0 and also made the scroll bit faster kindly check this https://jsfiddle.net/t8Lc4pjs/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM