1

I have a page which is basically a one pager. The menu uses # tags to scroll to different positions on the page. Now i added a shop to this page, which has the url : mypage.com/shop.

Now if i click in my menu on home. It scrolls to #home. But when i click on the shop it goes to mypage.com/shop and when i now click on the home link it goes to: mypage.com/shop#home. If i change the links in my menu from #home to mypage.com#home it works, but the scrolling doesnt work anymore. I made a jquery script to scroll to the different anchors, but this doenst work with a full url like: mypage.com#home.

jQuery(function($) {
$(".menu-item").on("click",function() {
  var href = $(this).attr('href');
  var elem = $(href).offset().top;
  $('html, body').animate({
    scrollTop:elem - 80
  },'slow');
});
});

is there a way to change this script to work with href links like : mypage.com#home ? Or is there a way to use #home only on the base url? So if i switch from mypage.com#home to mypage.com/shop and then back, that it will use mypage.com as the url instead of keeping /shop?

mrJQuery
  • 191
  • 9
  • Does this answer your question? [animated scrolling script prevents local anchor positions to be accessed from external links](https://stackoverflow.com/questions/36137841/animated-scrolling-script-prevents-local-anchor-positions-to-be-accessed-from-ex) – Johannes Feb 04 '21 at 12:52
  • @Johannes actually no. window.location.hash is empty or the old hash on the first click. the second click works, but i dont want to click twice. – mrJQuery Feb 04 '21 at 13:03

1 Answers1

0

i think you can solve this with window.location. for example

var getUrl = window.location;
console.log(getUrl);

that code give you current url. you can combine it with your href variable.

tsdln
  • 109
  • 8
  • if i use var href = window.location + $(this).attr('href'); it get unrecognized expression error: https://mypage.com#home – mrJQuery Feb 04 '21 at 13:08