ScrollTop: Smooth scrolling to ID prevents return to top

I am a beginner of jQuery. I have two functions on one page:

  • which is a smooth scroll to id
  • another that shows the back to the top element after the user scrolls a given distance.

Functions work independently, but when I combine them, as shown below, the "back to top" function does not work.

I think I missed something obvious and can use some help. Thank you


Update: This script shows the problem:

back to top jsfiddle If the smooth scroll block is disabled, the back to top function works.


jQuery(document).ready(function(){

  //smooth scrolling
  $('a[href^="#"]').on('click',function (e) {
    e.preventDefault();
    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
    'scrollTop': $target.offset().top -150}, 900, 'swing', function () {
    window.location.hash = target;});
  });

// Show or hide the back to top footer button
  $(window).scroll(function() {
    if ($(this).scrollTop() > 200) {
      $('.go-top').fadeIn(200);
    } else {
      $('.go-top').fadeOut(200);
    }
  });

  // Animate the scroll to top
  $('.go-top').click(function(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop: 0}, 900);
  });

});
+4
2

@DavidCara

<div id="top"></div>

<body> .

. jsfiddle

+1

html.

 <a onclick="$('html, body').animate({scrollTop: 0}, 900);" href="javascript:;">back to top </a>
0

Source: https://habr.com/ru/post/1538869/


All Articles