Select Page

If you want to make the browser go to a particular section with the id within the page or some different page if the id is not found, then you can do it with the following script. I used it in one of my projects and it is working fine. I am also using it with the scrollTo plugin for GSAP. So the animation is very smooth. You will need to include jQuery and GSAP js files for this on your page.

<!-- jQuery cdn -->
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>


<!-- GSAP  -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.1/ScrollToPlugin.min.js"></script>
// Register GSAP plugin
gsap.registerPlugin(ScrollToPlugin);

// Scroll to section when id is not found in the page
$(document).ready(function() {
  let headerHeight = 90;
  if(vw > 2200){
    headerHeight = 117;
  }
  
  if(window.location.hash) {
    let targetPosition = $(window.location.hash).offset().top - headerHeight;
    gsap.to(window, {duration: 2, scrollTo:  targetPosition });
  } 

  // Check # on anchor click
  $("a").click(function( event ) {
    let href = $(this).attr('href');
    let hash = href.substring(href.indexOf('#') + 1);
    if(hash){
      if ($('#' + hash).length) {
        event.preventDefault();
        
        let targetPosition = $('#' + hash).offset().top - headerHeight;
        gsap.to(window, {duration: 2, scrollTo:  targetPosition });
      }
    }
  });

  // Close side menu on link click
  $('.fullmenu .footer1__links a').click(function(){
    $('.fullmenu__menubtn').trigger('click');
  });
});