Scroll to Anchor Links

by yshrkn

HTML

<ul class="nav">
  <li><a href="#sec1">Sec1</a></li>
  <li><a href="#sec2">Sec2</a></li>
  <li><a href="#sec3">Sec3</a></li>
  <li><a href="#">To top</a></li>
</ul>

<section id="sec1">Section1</section>
<section id="sec2">Section2</section>
<section id="sec3">Section3</section>

SCSS

body {
  margin-top: 50px;
}

.nav {
  width: 100%;
  position: fixed;
  top: 0;
  background: #000;
  
  > li {
    display: inline-block;
    
    > a {
      color: #fff;
    }
  }
}

section {
  height: 1000px;
  padding-top: 50px;
}

#sec {
  &1 { background-color: sky; }
  &2 { background-color: yellow; }
  &3 { background-color: orange; }
}

JavaScript

$(function() {

  var scrollManager = (function() {

    var stateMap = {
    	isMoving: false
    };
    
    function addEventListeners() {
    
      $("a[href^='#']").on("click", function() {

    		if (!stateMap.isMoving) {
        
          var speed = 1000;
          var href= $(this).attr("href");
          var target = $(href == "#" || href == "" ? 'html' : href);
          var position = target.offset().top;

					if ($(window).scrollTop() === position) {
          	return;
          }

					stateMap.isMoving = true;
          
          $('body,html').animate({scrollTop:position}, speed, "swing", function() {
          	stateMap.isMoving = false;
          });
      	} else {
        	return;
        }
      });
    }

    function init() {
      addEventListeners();
    }

    return {
      init: init
    };
  }());


  function init() {
    scrollManager.init();
  }

  init();
});