Kim Carlo
Kim Carlo

Reputation: 1223

Open a link and autoscroll to specific div using jQuery

I have this code that when you open a link it will scroll to the specific div on that page.

collection.html

<a id='about' href="index.html">about</a>

index.html

<div id='#moreInfo>contents here</div>

<script>
   $(document).ready(function(){
          $('html, body').animate({
             scrollTop: $("#moreInfo").offset().top
           }, 1000);
   })
</script>

My problem is whenever I load the index.html, it always scrolls to the moreInfo div. What I want is when I'm on collection.html and I click on the about link, it will redirect to index.html then scroll smoothly to the moreInfo div.

I'll appreciate any answer.

Upvotes: 1

Views: 10085

Answers (3)

Smita Kagwade
Smita Kagwade

Reputation: 293

You can achieve smooth scrolling using html only

your page contains div like

<div id="sample">
</div>

You have to scroll to this div using

<a href="#sample">click here to scroll</a>

and simply use below code in your css

<style>
    html {
        scroll-behavior: smooth;
    }

</style>

Upvotes: 2

James Milani
James Milani

Reputation: 1943

An easy way to do this is just to have your link point to a location hash.

<a id='about' href="index.html#moreInfo">about</a>

Then, in your JavaScript you could just check if the person came from that link.

   $(document).ready(function(){
      if (window.location.hash == "#moreInfo") {
        $('html, body').animate({
           scrollTop: $("#moreInfo").offset().top
         }, 1000);
      }
   });

Upvotes: 5

Wesley Smith
Wesley Smith

Reputation: 19571

You can do this by setting a GET parameter on the link URL then reading that parameter when the next page loads:

collection.html

<a id='about' href="index.html?scrollTo=moreInfo">about</a>

index.html

<script>
   $(document).ready(function(){
          var scrollTo = getParameterByName('scrollTo');
          if(scrollTo!=''){
              $('html, body').animate({
                 scrollTop: $("#"+scrollTo).offset().top
               }, 1000);
          }
   });

   function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
</script>

Upvotes: 3

Related Questions