Toggle Hash feature not scrolling when using on-page link

Hi there,

I believe I’ve been through every forum post on this subject, but I believe something must be wrong in my JS provided in a previous post. I am trying to utilize the toggle hash feature in a v2 Tabs element.

Each item I’m linking to works perfectly when simply entering the url into the browser. But it doesn’t auto-scroll to the tab when using on-page links.

Ex: https://2020template.wmcircleofexcellence.com/#tab6

Here is the JS code I currently have on the page (pulled from another thread):

jQuery (function($){
$(window).load ( function() {  

if(window.location.hash) {
  var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
 

var header_height =  100 + $('#wpadminbar').height();      

var yloc = $('[data-x-toggle-hash="' + hash + '"]').offset().top - header_height;

$('html, body').stop().animate({
    scrollTop: yloc
}, 850);


}

} );

});

Can you help me determine what I’m doing wrong here?

Thank you!!

Hello @Nuera,

Thanks for writing in!

You are doing nothing wrong. The code is also correct. It’s just that the code only works for the hash in the url upon loading the page. This code does not include the click events from your menu or linked items. In you case, you will need to have this code:

jQuery (function($){
  $('a.x-img').on('click touchstart', function(e) {  
      var url = $(this).attr('href');
      var hash = url.substring(1); //Puts hash in variable, and removes the # character

      var header_height =  100 + $('#wpadminbar').height();      

      var yloc = $('[data-x-toggle-hash="' + hash + '"]').offset().top - header_height;

      $('html, body').stop().animate({
          scrollTop: yloc
      }, 850);
  });

  $(window).load ( function() {  
    if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character

      var header_height =  100 + $('#wpadminbar').height();      

      var yloc = $('[data-x-toggle-hash="' + hash + '"]').offset().top - header_height;

      $('html, body').stop().animate({
          scrollTop: yloc
      }, 850);
    }
  });
});

We would love to know if this has worked for you. Thank you.

ohhhhhhhhhhhhh man - this is workin like clockwork now!

Thanks Rue Nel!!!

You’re most welcome!
We’re just glad we were able to help you out.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.