0

Just wondering how to enable smooth scroll using full url.

This is the nav

<nav class="primary-nav">
  <ul>
    <li><a href="http://domainname.com/">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#services">Services</a></li>
    <li><a href="http://domainname.com/contact">Contact</a></li>
  </ul>
</nav>

Would like to use

<nav class="primary-nav">
  <ul>
    <li><a href="http://domainname.com/">Home</a></li>
    <li><a href="http://domainname.com/#about">About</a></li>
    <li><a href="http://domainname.com/#services">Services</a></li>
    <li><a href="http://domainname.com/contact">Contact</a></li>
  </ul>
</nav>

and this is the jQuery code used to scroll to sections on the page.

function smoothScroll(duration) {
 $('a[href^="#"]').on('click', function (event) {
  var target = $($(this).attr('href'));
   if (target.length) {
     event.preventDefault();
     $('html, body').animate({
      scrollTop: target.offset().top
     }, duration);
   }
  });
 }

Any help would be great thanks.

Ollie
  • 13
  • 4
  • Are you asking if you can click on a # from a page where the # doesn't exist and go to the page where it does exist, then scroll to that #? – Tom Sep 09 '16 at 11:25
  • If the domain is in there it will reload the page / go to a new page. If you want to go to a new page and then scroll, you would need to do look for the page load event and look for a '#' in the URL. – Paul Thomas Sep 09 '16 at 11:35
  • Similar to:- [https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link](https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link) – Jasmeet Singh Oct 03 '17 at 08:36

1 Answers1

0

As far as I understand you want to stay on the same page, just for some reason you want your internal links to be absolute.

To achieve internal linking with absolute URLs you could change it like that:

JavaScript:

 var duration = 1000;
 var domainname = 'http://domainname.com/';

 $('a[href^="'+domainname+'#"]').on('click', function (event) {
   var target = $(this).attr('href');
   if (target.length) {
     event.preventDefault();

     target = $( target.replace(domainname, '') );

     $('html, body').animate({
        scrollTop: target.offset().top
     }, duration);
   }
  });

Explanation: You change the selector so that it not activates on URLs like '#about' but 'http://domainname.com/#about'. Then you cut off the domain name part and you will have a internal link like '#about' again.

Fiddle: https://jsfiddle.net/u5dL9rt3/

Michael Troger
  • 3,336
  • 2
  • 25
  • 41