Adam Griffiths
Adam Griffiths

Reputation: 782

Don't block scrolling animation when setting scroll programmatically via jQuery

Here's a full codepen of the situation I will describe in detail below: https://codepen.io/Adam0410/full/MGXjaz/

The javascript contained in the codepen (the core of the issue) is below:

var collapsed = false;

$(window).scroll(function(){

     var scroll = window.pageYOffset || document.documentElement.scrollTop;

     if (scroll > 207 && !collapsed) {

      $("#header").css({
          position: "fixed",
          height: "50px",
          "line-height": "50px"
      });

       $("#content").css("margin-top", "207px");
        $(document).scrollTop(scroll - 50);

        collapsed = true;

    } else if (scroll < 155 && collapsed) {

        $("#header").css({
            position: "static",
            height: "257px",
            "line-height": "257px"
        });

        $("#content").css("margin-top", "0");
        $(document).scrollTop(scroll + 50);
        collapsed = false;

    }

});

I am attempting to make a large header that is part of the flow of the document, that then turns into a smaller fixed header as you scroll down past it. I want the action of the user scrolling to be smooth during this process.

If you view the pen on mobile (or use chrome's device toolbar) with smooth scrolling and scroll slowly around the breakpoint where the header changes you can see it's completely smooth.

However if you view it on a desktop (with chrome again, or any other browser) the scrolling with a scroll wheel is done in 100-pixel increments. For this reason once again if you scroll around the breakpoint where the header changes you can see it is not smooth.

This occurs since the 100-pixel scrolling doesn't occur instantly and in the process of changing the scrollTop of the document the 100-pixel scrolling animation gets canceled. Is there any way to detect and resume this scrolling animation once I've set the scrollTop property?

Upvotes: 1

Views: 238

Answers (2)

hallleron
hallleron

Reputation: 1992

I have another approach with the help of a very small plugin called smoothwheel (Get it here). I extended the answer of @Rohith Murali and created an example. Have a look here:

https://codepen.io/anon/pen/NMBdpx

The plugin itself enables you to scroll smoothly with low impact on performance. Does this fit your needs?

Upvotes: 2

Rohith Murali
Rohith Murali

Reputation: 5669

Please check https://codepen.io/anon/pen/PeabEL

Changed the js to

$(window).scroll(function(){
    var scroll = window.pageYOffset || document.documentElement.scrollTop;
  var newHeight = 50;
   if(257-scroll>50)
     newHeight = 257-scroll;
    $("#header").css({
        position: "fixed",
        height: newHeight+"px",
        "line-height": newHeight+"px",
      }); 
});

also added

#content {
...
  margin-top:257px;
}

and,

#header {
...
position: fixed;
}

Upvotes: 2

Related Questions