Darko
Darko

Reputation: 930

WordPress scroll to ID from different page using jQuery

I'm trying to make anchor links to work from external pages with "animate" and "scroll-top" in WordPress, but when I try to go to the specific id using anchor link form a different page, page scrolls to the bottom instead to the anchor id, except the first link only, it works as it supposed.

     function foo(){
        $('#masthead #site-navigation a[href*="#"]:not([href="#"])').click(function() {

       // top offstet
       var offset = 10;
       // get target    form hash
       var target = $(this.hash);
       // Get hash from this
       var hash = $(this).attr('href');
       // Get URL from injected JavaScript page object siteInfo
       var host = siteInfo.siteUrl;

       // if home   
       if($('body.home').length > 0){

          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

          if (target.length) {
             $('html, body').animate({
               scrollTop: target.offset().top + offset
             }, 1000);
           return false;
         }
      } 
      else {
         window.location = host+"/#"+hash.substring(1);
         return false;
       }
    }); 
  }

 foo();

Upvotes: 0

Views: 605

Answers (1)

Femi Oladeji
Femi Oladeji

Reputation: 365

Your target has to be a valid dom element What you have below makes target a string

target = "/#"+hash.substring(1);

You need the jquery selector along with that

target = $('#'+hash.substring(1));

target now becomes a valid dom element that the .offset().top will return a value for

P.S If the page will reload, then the .animate() has to be outside of the .click() function because the js script itself will be loaded all over again

$('#masthead #site-navigation a[href*="#"]:not([href="#"])').click(function() {
  var offset = 10; // <-- change the value here
  // Get hash from this
  var hash = $(this).attr('href');
  // Get URL from injected JavaScript page object siteInfo
  var host = siteInfo.siteUrl;
  window.location = host+"/#"+hash.substring(1);
});

you only need the section below on the js of the target page. It gets the current url and gets the text after the # which should correspond to the id of the div you're scrolling to

var currentUrl = window.location.href;
if(currentUrl.includes('#')) {
    var urlArray = currentUrl.split('#');
  // gets the dom that has the id evaluated from `hash.substring(1)`
  target = $('#'+urlArray[1]);
  $('html, body').animate({
    scrollTop: target.offset().top + offset
  }, 1000);
}

Upvotes: 1

Related Questions