Javascript scroll to element with animation onclick - Stack Overflow

I'm just starting out with JS and struggling. I got this lovely bit of code from Adam Khoury and i

I'm just starting out with JS and struggling. I got this lovely bit of code from Adam Khoury and it's working beautifully animated scrolling down the page to the target element.

The ul is within a fixed position navigation bar.

My question is: what code would be needed to make the animation scroll both up and down when the anchor in the nav is clicked?

var scrollY = 0;
var distance = 10;
var speed = 24;

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

function resetScroller(el) {
  var currentY = window.pageYOffset;
  var targetY = document.getElementById(el).offsetTop;
  var animator = setTimeout('resetScroller(\'' + el + '\')', speed);
  if (currentY > targetY) {
    scrollY = currentY - distance;
    window.scroll(0, scrollY);
  } else {
    clearTimeout(animator);
  }
}
<ul class="main-nav">
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('about');">
      About</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('testimonials');">
      Testimonials</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('contact');">
      Contact</a>
  </li>
</ul>

<hr style="margin: 25em 0;" />

<div id="about" class="navButton">
  <p>About lorem ipsom....</p>
</div>

<div id="testimonials" class="navButton">
  <p>Testimonial lorem ipsom....</p>
</div>

<div id="contact" class="navButton">
  <p>Contact lorem ipsum</p>
</div>

I'm just starting out with JS and struggling. I got this lovely bit of code from Adam Khoury and it's working beautifully animated scrolling down the page to the target element.

The ul is within a fixed position navigation bar.

My question is: what code would be needed to make the animation scroll both up and down when the anchor in the nav is clicked?

var scrollY = 0;
var distance = 10;
var speed = 24;

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

function resetScroller(el) {
  var currentY = window.pageYOffset;
  var targetY = document.getElementById(el).offsetTop;
  var animator = setTimeout('resetScroller(\'' + el + '\')', speed);
  if (currentY > targetY) {
    scrollY = currentY - distance;
    window.scroll(0, scrollY);
  } else {
    clearTimeout(animator);
  }
}
<ul class="main-nav">
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('about');">
      About</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('testimonials');">
      Testimonials</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('contact');">
      Contact</a>
  </li>
</ul>

<hr style="margin: 25em 0;" />

<div id="about" class="navButton">
  <p>About lorem ipsom....</p>
</div>

<div id="testimonials" class="navButton">
  <p>Testimonial lorem ipsom....</p>
</div>

<div id="contact" class="navButton">
  <p>Contact lorem ipsum</p>
</div>

Share Improve this question edited Dec 18, 2014 at 22:24 Tomáš Zato 53.5k63 gold badges310 silver badges828 bronze badges asked Dec 18, 2014 at 20:09 chilledMonkeyBrainchilledMonkeyBrain 1411 gold badge4 silver badges15 bronze badges 4
  • You got any live example of this? – Playmaker Commented Dec 18, 2014 at 20:13
  • In place of 'else {clearTimeout(animator);}', try 'else {scrollY = currentY-distance; window.scroll(currentY, scrollY);}' – Playmaker Commented Dec 18, 2014 at 20:15
  • Are you willing to use jQuery? – Dave Commented Dec 18, 2014 at 20:16
  • Never use setTimeout with strings! It's like using evil eval. Use functions instead: setTimeout(function(){autoScrollTo(el)}, 24) – Oriol Commented Dec 18, 2014 at 20:36
Add a ment  | 

3 Answers 3

Reset to default 2

Thanks to Dave for steering me away from javascript and on to JQuery. This bit of code is really newb friendly. You don't need to edit it at all, just paste it in your index.html and bam! and it works

<header class="main-header">

                <ul class="main-nav">
                <li><a href="#about">About</a></li>
                <li><a href="#testimonials">Testimonials</a></li>
                <li><a href="#contact">Contact</a></li>
                </ul>
        </header>    

<!-- SMOOTH SCROLL -->
        <script src="http://ajax.googleapis./ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
        $(function() {
          $('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
                }, 1000);
                return false;
              }
            }
          });
        });
        </script>
        <!-- End of SMOOTH SCROLL -->   

If you're willing to use jQuery this will be much simpler. All you have to do is get the .offset() top of the element you want to scroll to and then animate the scrollTop position using jQuery .animate() function.

function autoScrollTo(el) {
    var top = $("#" + el).offset().top;
    $("html, body").animate({ scrollTop: top }, 1000);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="main-nav">
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('about');">
      About</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('testimonials');">
      Testimonials</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('contact');">
      Contact</a>
  </li>
</ul>

<hr style="margin: 25em 0;" />

<div id="about" class="navButton">
  <p>About lorem ipsom....</p>
</div>

<div id="testimonials" class="navButton">
  <p>Testimonial lorem ipsom....</p>
</div>

<div id="contact" class="navButton">
  <p>Contact lorem ipsum</p>
</div>

I don't have time to put this all in a page to really test it out, but what I would try first is something along these lines:

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

So instead of clearing the timeout when currentY is greater than the targetY-distance, it scrolls in the opposite direction? Might not work, but worth a shot...

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744285804a4566789.html

相关推荐

  • Javascript scroll to element with animation onclick - Stack Overflow

    I'm just starting out with JS and struggling. I got this lovely bit of code from Adam Khoury and i

    7天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信