I have a page for which I've got smooth scrolling anchor links, using jquery 1.10 and the code listed below. The smooth scrolling works fine. After clicking the "back to top" link, an item is added to the user's history and visible in the url (as domain.com/page#header
), which is expected.
However, because this messes up the url and breaks the functionality of the back button I'm trying to remove the anchor from the url and the browser history. I've tried several methods for removing an anchor link or a history item, but they all cause conflicts with the code for the smooth scrolling.
So my question is, does anyone know how I can remove this anchor from the url and remove the last history item, after the smooth scrolling is done?
An example: http://jsfiddle.net/CQywc/5/
EDIT: I didn't delete this question because it was difficult for me to figure out exactly what I needed to do, even when I saw the answers to the other questions (they address a slightly different issue, and didn't explicitly resolve the added history item). So I'll leave this here for people who have the same problem I had.
Code for smooth scrolling:
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
I solved it by commenting the following bit of code:
location.hash = target; // comment by putting two forward slashes in front of this line of code
Which explicitly adds the hash to the url when uncommented. Thanks to Jeff B, in this question. It also solves the added history item, so the back button works as expected again.