0

I am currently using this code I found to autoscroll to anchors:

$(function() {
    $('nav a[href*=#]').bind('click',function(event){
        var $anchor = $(this);

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - 100
        }, 1000);
        event.preventDefault();

    });
});

What can I add to make sure that the #anchor gets added to the URL when clicked?

I have seen this used, but I'm not sure how to add it..

function() {
        if(history.pushState) {
            history.pushState(null, null, target);
        }
        else {
            location.hash = target;
        }
      });

Thanks very much!!!

Reuben
  • 2,701
  • 6
  • 31
  • 47

1 Answers1

2

Run it when the animation is done: (nice demo here)

$(function () {
    $('nav a[href*=#]').on('click', function (event) {
        var $anchor = $(this),
            name = $anchor.attr("href").match(/#(.+)/i)[1];

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - 100
        }, 1000, function () {
            if (history.pushState) {
                history.pushState(null, null, "#" + name);
            } else {
                location.hash = name;
            }
        });
        event.preventDefault();
    });
});

WORKING DEMO: http://jsfiddle.net/DerekL/uPS9W/show

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247