simplesimon February 2016

Scroll Automation Wont Stop on Last Link

I have a javascript function that's not quite working properly. It works brilliantly for all links except the last. When that link is triggered it scrolls to the bottom and then doesn't allow you to scroll up...despite my best efforts.

Maybe my approach is completely wrong.

Here is the markup:

  <nav>
    <ul>

      <li>
        <a id="home" href="#" onclick="return false">home</a>
      </li>

      <li>
        <a id="services" href="#" onclick="return false">services</a>
      </li>

      <li>
        <a id="portfoliolink" href="#" onclick="return false">portfolio</a>
      </li>

      <li>
        <a id="contactlink" href="#" onclick="return false">contact</a>
      </li>

    </ul>

  </nav>

And javascript:

function smoothScroll(){
  if (window.addEventListener){
    document.getElementById('home').addEventListener("click", scrollToHome, false);
    document.getElementById('services').addEventListener("click", scrollToServices, false);
    document.getElementById('portfoliolink').addEventListener("click", scrollToPortfolio, false);
    document.getElementById('contactlink').addEventListener("click", scrollToContact, false);
  }
};

function scrollToHome(){
  var scrollY = 0;
  var distance = 40;
  var speed = 24;
  var currentY = window.pageYOffset;

  var targetY = document.getElementById('chris-misterek').offsetTop;
  var bodyHeight = document.body.offsetHeight;
  var yPos = currentY + window.innerHeight;
  var animator = setTimeout('scrollToHome("chris-misterek")',24);

  if(currentY < targetY-distance){
      scrollY = currentY+distance;
      window.scroll(0, scrollY);
    }
  else {
      clearTimeout(animator);
    }
};

function scrollToServices(){
  var scrollY = 0;
  var distance = 10;
  var currentY = window.pageYOffset;

  var targetY = document.getElementBy        

Answers


simplesimon February 2016

Figured out that I needed to add a greater than equal to for the if(yPos > bodyHeight) statement correct code looks like this:

function scrollToContact() {
    var currentY = window.pageYOffset;
    var targetY = document.getElementById('contact').offsetTop;
    var bodyHeight = document.body.offsetHeight;
    var yPos = currentY + window.innerHeight;
    var animator = setTimeout('scrollToContact("contact")',24);
    if(yPos >= bodyHeight){
        clearTimeout(animator);
    } else {
        if(currentY < targetY-distance){
            scrollY = currentY+distance;
            window.scroll(0, scrollY);
        } else {
            clearTimeout(animator);
        }
    }
};

Post Status

Asked in February 2016
Viewed 3,745 times
Voted 4
Answered 1 times

Search




Leave an answer