edward edward - 25 days ago 8
Javascript Question

script is preventing anchor link from appearing in URL

I'm using some jQuery I came across to smooth the scrolling to anchor links within a page. I now realize that there is something in this script that is preventing the anchor link (e.g., '#top') from appearing in the URL -- and I do want the anchor link in the URL. Can someone tell me what part of this is turning off the default behavior and what I could do to turn it back on?

<script>
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
return false;
}
}
});
});
</script>

Answer

I have not tested this out on a real page, but on end of the animate, you can set the hash.

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var hash = this.hash,
          target = $(hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 500, function(){
            window.location.hash = hash;
        });
        return false;
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#foo">bottom</a><br/>
A<br/>B<br/>C<br/>D<br/>
E<br/>F<br/>G<br/>H<br/>
I<br/>J<br/>K<br/>L<br/>
M<br/>N<br/>O<br/>P<br/>
Q<br/>R<br/>S<br/>T<br/>
U<br/>V<br/>W<br/>X<br/>
Y<br/>Z<br/>
<p id="foo">HEY</p>