简体   繁体   中英

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.

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);
      }
   });

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM