aiddev
aiddev

Reputation: 1429

mcustomscrollbar and scrolling to corresponding section

Here is my fiddle

(function($){
    $(window).load(function(){
        $(".sections").mCustomScrollbar({theme:"light-3"});
    });
    jQuery("ul.subMenu li a").each(function(){
        jQuery(this).click(function(){
            $thisId = jQuery(this).attr('href');
            $('html,body').animate({scrollTop: $thisId.offset().top}, 'fast');
        });
    });
})(jQuery);

I am using mCustomScrollbar and when you click on every link it should scroll to corresponding section. But now it just jumps to clicked section no scrolling, I wrote scrolling with animate function but no success.

Upvotes: 0

Views: 5771

Answers (1)

spenibus
spenibus

Reputation: 4409

After a bit of fiddling, I got the auto-scrolling to work but I had to disable mCustomScrollbar, clearly not ideal. For some reason, mCustomScrollbar seems to interfere with jQuery's .animate().

So I went looking for the equivalent of .animate() in mCustomScrollbar and found this:

scrollTo

Usage $(selector).mCustomScrollbar("scrollTo",position,options);

Call the scrollTo method to programmatically scroll the content to the position parameter (demo).

mCustomScrollbar documentation: scrollTo

From there, all it took was a little rewrite:

(function(){

    $(window).load(function(){
        $(".sections").mCustomScrollbar({theme:"light-3"});
    });

    // container ref
    var sections = $('.sections');

    $("ul.subMenu li a").each(function(){

        // link ref
        var link = $(this);

        // section ref
        var section = $(link.attr('href'));

        link.click(function(){

            sections.mCustomScrollbar("scrollTo", section.position().top, {

                // scroll as soon as clicked
                timeout:0,

                // scroll duration
                scrollInertia:200,
            });

            // disable original jumping
            return false;
        });
    });
})();

Notes

Demo

mCustomScrollbar's scrollTo on jsfiddle

Upvotes: 3

Related Questions