Search code examples
javascriptjquerysmooth-scrolling

Smooth scroll no anchor only jQuery


I have a jQuery script that allows me to scroll horizontally but it's a rusty old scroll, and I want to make it smooth without changing the entire code.

I want to change the this.scrollLeft -= (delta * 90); with an .animate but I'm a beginner with jQuery.

Here's my code so far :

$(document).ready(function() {

    $('html, body, eall, *').mousewheel(function(e, delta) {
        this.scrollLeft -= (delta * 90);
        e.preventDefault();
    });
});

Solution

  • First only select the elements that must call your event callback and not $('html, body, eall, *') like your question shows you are doing.

    For example, add a .horizontalScroll class to the desired elements and then $('.horizontalScroll)

    Then you can do something like this to make a smoother scroll:

    var scroll = $(this).scrollLeft() - (delta * 90);
    $(this).stop(true).animate({
          scrollLeft: scroll
    }, 200);
    e.preventDefault();
    

    See this working demo (scroll inside div#scroll, tweak (delta * 90) and animate duration argument 200 to get the desired smoothness.