Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smoothscroll doesn't work in chrome but works in other browsers

I have a button (it is a Font awesome icon), which if you click on it it scrolls to a specific div. In Safari it worked but now I am testing it in Chrome it doesn't work.

The script I am using (jQuery)

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});

The button

<a href="#arrow-down-click">
<i class="fa fa-angle-down fa-4x arrow-down" aria-hidden="true"></i>
</a>

How to get this working in Chrome (and maybe other browsers I didn't tested yet) too?

EDIT (also in a comment):

I just found out: if I change in css html { overflow: hidden; } to auto and body { overflow: auto; } to hidden, the animation works. But the problem is: I can't scroll from the top down without using the button to go to part 2, and if I am on part 2 I can't scroll anywhere (so not back to the top or to part 3).. Does someone has an idea for that?

EDIT 2 Right now I have this: https://jsfiddle.net/jk1540oc/. It goes to the div I direct to, but it doesn't animate anymore (not in Chrome and not in Safari). You also can't scroll down twice by using the button.

like image 893
Julian Avatar asked Oct 18 '22 10:10

Julian


1 Answers

I recommend keeping html, body { overflow: hidden, height: 100% } and then a wrapper div with { overflow: auto; height: 100% }

<html>
  <body>
    <div id="site-wrapper"> everything in here </div>
  </body>
</html>

This is a pattern I have used for a very long time and it has saved me a lot of headache. Then, do all of your scrolling animations on the div. Here's a working demo:

https://jsfiddle.net/b4uje52o/2/

like image 182
Ryan Wheale Avatar answered Nov 04 '22 00:11

Ryan Wheale