0

I'm trying to put a smooth scroll in location.hash, but it seems it's not working.

How to fix this?

JS

function test_function(){
    window.location.hash = '#divid';
    jQuery(document).ready(function($){
        $('html, body').animate({ scrollTop: $(test_function).target.offset().top }, 1000);
    });
}

HTML

<div>
<a href="<?php echo $_POST['referrer'] ?>#divid">Find a store</a>
</div>
User014019
  • 1,215
  • 8
  • 34
  • 66

2 Answers2

1

I feel, there was some console error with your above code to scrollTop, because $(test_function).target. would come undefined. You need to target the proper element to navigate to it smoothly. Below is the sample snippet you can work on.

function test_function() {
  $('html, body').animate({
    scrollTop: $("#divid").offset().top
  }, 2000);
}
#divid {
  position: absolute;
  top: 800px;
  width: 200px;
  height: 200px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="test_function(this)" href="#">Find a store</a>
<div id="divid"></div>
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
0

Simple answer i'm find here , here you can also use multiple anchor tag and different div id.

<a href="<?php echo $_POST['referrer'] ?>#divid">Find a store</a>

<script type="text/javascript">
    $(function() {
      $("a[href*='#']:not([href='#'])").click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 2000);
          return false;
        }
      }
     });
    });
</script>

<div id="divid">Scroll Section</div>
Kishan Chauhan
  • 1,216
  • 1
  • 12
  • 19