0

On my wordpress site my smooth scroll to anchor script is not working like expected. It fires the "alert" and scrolls to the page but without any animation.

$(document).ready(function($){

/*------------------------------------*/
/* SMOOTH SCROLL */
/*------------------------------------*/
$('a[href^="#"]').on('click',function (e) {
    alert("Step 1");
    e.preventDefault();

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

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});    
public9nf
  • 1,311
  • 3
  • 18
  • 48
  • I think this is a duplicate: http://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link – Marcin Dusza Aug 02 '16 at 08:16
  • 3
    Seems to work correctly for me, assuming I'm using it as expected: https://jsfiddle.net/k2923ck9/2/ – DBS Aug 02 '16 at 08:19
  • 1
    either you want the delay to more slower, because there is nothing wrong there, and @DBS has confirmed this in his fiidle. To add more delay increase your `900ms` – Shekhar Pankaj Aug 02 '16 at 08:21
  • I added more delay (up to 5000). When i click the link the delay is 5000ms but its not scrolling smoothly, its just jumping to the section like a normal anchor link. Is it possible there is some problem with the animate function? – public9nf Aug 02 '16 at 09:21
  • Can you create a reproducing example? At the moment everything you've posted seems to work as expected, so it's very difficult to try to help. – DBS Aug 02 '16 at 10:44

1 Answers1

0

I added this code to end of the functions.php file on my wordpress site and it works great for me with anchor links.

function add_javascript() {
    ?>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("a").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){
        window.location.hash = hash;
      });
    }
  });
});
</script>
    <?php
}
add_action('wp_head', 'add_javascript');
webworm84
  • 324
  • 2
  • 13