Ollie Ollie - 3 years ago 145
jQuery Question

jQuery smooth scroll full url including id

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.

Answer Source

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/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download