javascript - get back to top of page with a smooth scrolling and anchor name into url -


i used following code this link have smooth scrolling page , callback makes appears name of anchor once scrolling done (i calling callback of .animate) :

$(function() {     $('a[href*=#]:not([href=#])').click(function(event) {       event.preventdefault();       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) {         var hash = this.hash; // 'this' not in scope in callback       $('html,body').animate({ scrolltop: target.offset().top - 55}, 300, function() {         location.hash = hash;         });        return false;       }          }          });       //executed on page load url containing anchor tag.     if($(location.href.split("#")[1])) {     var target = $('#'+location.href.split("#")[1]);     if (target.length) {       var hash = this.hash; // 'this' not in scope in callback     $('html,body').animate({ scrolltop: target.offset().top - 55}, 300, function() {       location.hash = hash;       });      return false; } } }); 

my issue don't know how able return top of page when click on button of browser, i.e return previous state. example, first on page (http://example.com/index.html), click on anchor, scrolling down anchor , after anchor name set url(http://example.com/index.htm#anchor). if click on button of browser, redirected top of page. moment, above script, nothing happens.

any welcome,

thanks

update :

following matthew lymer's answer, made tests adding :

$(document).ready(function(event) {       var target = window.location.href.split("#")[1];       if (target.length) {         var hash = this.hash; // 'this' not in scope in callback       $('html,body').animate({ scrolltop: target.offset().top}, 300, function() {         location.hash = hash;         });       return false;       } 

but animate scrolling top of page (wanted when press button) doesn't work

console prints :

  type error: target undefined 

just reuse function, instead of onclick, trigger happen when document ready;

$(document).ready(function(){     ...  }); 

instead of setting value of target $(this).hash, take hash part of url using

target = window.location.href.split("#"); target = target[1]; 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -