window.scrollTo not scrolling to provided id

Viewed 1076

I am working on a single document file. I want to scroll to the desired section with id="projectpage" when an anchor with id="about" is clicked.

<a class="nav-link page-scroll"  href="" id="about">About Me</a>

<section id="aboutpage">

I tried using

$('a#about').click(function(){
    $(window).scrollTo(0, document.getElementById('projectpage').offsetTop);
    
  });

or even

$('#about').click(function(){
    $(window).scrollTo(0, document.getElementById('projectpage').offsetTop);
    
  });

but nothing works.

When I click on the anchor with id="about", it just redirects me to the index.html(the main HTML with all document) file itself rather than going to the offsetTop of id="projectpage".

2 Answers

You need to prevent the default behavior of an anchor.... Using .preventDefault()

And replace $(window) for just window... You don't need jQuery to lookup for the window when you wish to apply a vanilla JS method on it.

$('#about').click(function(e) {
  e.preventDefault()
  window.scrollTo(0, document.getElementById('aboutpage').offsetTop);
});
section{
  height: 200px;
  border-top: 2px solid grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="nav-link page-scroll" href="" id="about">About Me</a>

<section id="somethingElse1">...</section>
<section id="somethingElse2">...</section>
<section id="somethingElse3">...</section>
<section id="aboutpage">About</section>
<section id="somethingElse4">...</section>
<section id="somethingElse5">...</section>

I made a small example for you using scrollIntoView(). Also, take into account the need for event.preventDefault() to disable the default ability to click on the tag a.

In addition, scrollIntoView() has a parameter with an animation transition effect:

behavior: "smooth"

Note: since you are using jquery, I see no point in casting to an element like:

document.getElementById('aboutpage')

Appeal, as in jquery:

$("#aboutpage")[0]

$('a#about').click(function(event){
  event.preventDefault();
    $("#aboutpage")[0].scrollIntoView({
    behavior: "smooth"
  }); 
});
#first {
  width: 100%;
  height: 1000px;
  background-color: green;
}

#aboutpage {
  width: 100%;
  height: 1000px;
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="nav-link page-scroll"  href="" id="about">About Me</a>

<section id="first"></section>
<section id="aboutpage"></section>

Related