0

I'm trying to autoscroll to some specific place/ID without JQuery. Now I have this block of code with JQuery, this send me to a specific ID with autoscroll.

$(function() {
  $('a[href*=#]').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top
    }, 900, 'linear');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#one">one</a>
<div id="one"></div>

And I'm looking to do some similar effect but with JavaScript, any idea?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sr Jefers
  • 87
  • 4
  • 14

1 Answers1

1

This is the best you can do for a start when using javascript only to scroll with a smooth effect using window.scroll and element.getBoundingClientRect().top, see a demo below

#one {
  margin-top: 1000px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#one">one</a>

<div id="one">down-here</div>

<script type="text/javascript">
  (function() {
    let anchors = document.querySelectorAll('a[href*="#"]');

    anchors.forEach(function(anchor) {
      anchor.addEventListener('click', function(e) {
        e.preventDefault();

        let id = this.getAttribute("href");
        let targetElement = document.querySelector(id)
        let scrollHeight = targetElement.getBoundingClientRect().top + window.scrollY;

        //scroll with smoooth effect
        window.scroll({
          top: scrollHeight,
          behavior: 'smooth'
        });
      });

    })

  })();
</script>
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
  • Oh no! How can do it but just with **JavaScript** but without Jquery :( – Sr Jefers Jun 13 '18 at 02:46
  • the scroll already uses javascript there isnt any jquery , the only jquery thing is the `.on('click',function())`you can replace it by `addEventListener('click', function(e) {` i have updated the code, check again and mark the answer as correct if it works for you @SrJefers – Muhammad Omer Aslam Jun 13 '18 at 03:00