yves amsellem
yves amsellem

Reputation: 7234

jQuery scrollTop through anchors preserving browser history

I'm trying to add smooth transitions between a page anchors.

In the following code, transitions are working but browser history do not remember the anchor navigation. Using browser back button fails. Removing preventDefault() make everything works, but the page flashes with the target tag content before scrolling to it from the previous page position.

I have tried plugins — like address — without success. So, what is the easy way to scroll through anchors preserving browser history?

$('a').click(function(e) {
  e.preventDefault();

  var href = $(this).attr('href');
  $('html, body').animate({
     scrollTop: $(href).offset().top}, 'slow', 'swing'
  );
});

Upvotes: 1

Views: 1246

Answers (2)

Tim Dodd
Tim Dodd

Reputation: 251

Replace

    $("html,body").animate({

with this

    $("html:not(:animated),body:not(:animated)").animate({

It's also good practice to use different variable names from other values e.g. HREF used for variable name and is also the link attribute.

Upvotes: 0

yves amsellem
yves amsellem

Reputation: 7234

Solved by this question. The answer implies a nice jQuery library: smoothanchors.

Upvotes: 2

Related Questions