Sr Jefers
Sr Jefers

Reputation: 129

How can I scroll to some specific place/ID with JavaScript?

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?

Upvotes: 0

Views: 62

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23778

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>

Upvotes: 1

Related Questions