Burger Sasha
Burger Sasha

Reputation: 175

How to use scroll animations inside smooth scrollbar

I am using smooth scrollbar https://github.com/idiotWu/smooth-scrollbar#demo which has stopped my scroll animation (below) from working.

I want to understand why, as well as if there is a way to use both? Code:

EDIT: I have included my code with the JS to initialise smooth scrollbar commented out to demonstrate the scroll animation

$(function() {

var header = $("header");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();    
        if ($(window).scrollTop() > 20) {
            header.addClass('scroll');
        } else {
            header.removeClass('scroll');
    }
   
   
    });
});    
body {
	margin:0;
	padding:0;
	font-size: 1rem; 
	font-family: sans-serif;

}

#scroll {
  width: 100%;
  height: 150vh;
  overflow: auto;
}


header {
    width: 100%;
    padding: 4rem 10rem 1.5rem;
    font-size:1.5rem;
    z-index: 9997;
    mix-blend-mode: difference;
    opacity: 1;
    transition: all ease-in 0.3s;
    position: fixed;
    text-transform: uppercase;
    margin: 0 auto;
}




header.scroll {
    padding: 1.5rem 10rem 1.5rem;
}
<!-- CSS -->
<link rel="stylesheet" href="https://unpkg.com/smooth-scrollbar@latest/dist/smooth-scrollbar.css">



<body>
<main id="scroll" data-scrollbar>

<header>Test</header>


</main>
</body>

<!-- JS -->
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>  
        <!-- script src="https://unpkg.com/smooth-scrollbar@latest/dist/smooth-scrollbar.js"></script>
        
        <script> 

            Scrollbar.initAll();
            Scrollbar.detachStyle();

        </script -->

var header = $("header");
$(window).scroll(function() {
    var scroll = $(window).scrollTop();    
    if ($(window).scrollTop() > 20) {
        header.addClass('scroll');
    } else {
        header.removeClass('scroll');
}

Upvotes: 0

Views: 759

Answers (1)

Dalibor Ilic
Dalibor Ilic

Reputation: 11

Instead of using $(window).scrollTop() use Scrollbar.scrollIntoView(element,options), something like:

scrollbar.scrollIntoView(document.querySelector('#anchor'), {
  offsetLeft: 34,
  offsetBottom: 12,
  alignToTop: false,
  onlyScrollIfNeeded: true,
});

More in the official docs: https://github.com/idiotWu/smooth-scrollbar/blob/develop/docs/api.md#scrollbarscrollintoview

Upvotes: 1

Related Questions