Wednesday, 11 May 2016

jQuery : Scroll to URL HASH Tag / ID location on page when dynamic page height

www.example.com/index.html#foo

IF you want to smooth scroll using  #foo
It will not work directly when your page adding dynamic content and increasing page height.

Solution :
1)  On document ready find hash tag value in URL
2) Find whether it's actually exists in page or not
3) If you found that hash tag id anywhere within page then scroll to that section.

Following is jquery code for that.

<script type="text/javascript">
    $( document ).ready(function() {

        var hashnew = document.URL.substr(document.URL.indexOf('#')+1)
              
        if ($("#"+hashnew).length) {
               
                 $('html, body').animate({
                       scrollTop: $("#"+hashnew).offset().top
                 }, 2000);
   
        }
   
    });
</script>

No comments:

Post a Comment