-3

I'm new to JS, trying to make the following code work so that the homepage automatically scrolls on load and anchor links on other pages scroll smoothly on click...

<script>

    $(function(){
    $('html, body').animate({
    scrollTop: $('.destination').offset().top
    }, 2000);
    return false;

    $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 2000);
        return false;
      }
    }
   });
   });

</script>

Any help would be much appreciated!

Thanks, Andreas

Andreas
  • 21
  • 1
  • 4

1 Answers1

0

It is because you are closing the function by returning false earlier. Try:

 $(function(){
    $('html, body').animate({
    scrollTop: $('.destination').offset().top
    }, 2000);

    $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 2000);
        return false;
      }
    }
   });
   });
deleted
  • 772
  • 1
  • 6
  • 19
  • That's awesome thanks! I was about to say that it works when I simply change the order of the functions. Now I assume that's because if I do that, scrolling takes place (on load) before a click can happen...? – Andreas Sep 19 '15 at 11:43
  • @Andreas To my knowledge yes. – deleted Sep 19 '15 at 11:56