I'm trying to use Smooth Scroll on my site, but I need the anchor id on URL, to give the funcion of browser Back Button. The problem is: I need the #anchor to show up before 400 ms, but I don't know how can I call that variable in my script.
$(document).ready(function(){
$('a[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) {
var targetOffset = $target.offset().left;
$('html,body')
.animate({scrollLeft: targetOffset}, 400);
var timer = setTimeout(function() {
window.location.href = '#[anchor]';
}, 400);
return false;
}
}
});
});
The window.location.href = '#[anchor]';
change the url but not with the anchor name. How can I change that?
The anchor is stored in the hash
variable, see the example and check the comments:
if (target.length) {
var _this = this; // first save the reference to 'this'
var targetOffset = $target.offset().left;
$('html,body').animate({scrollLeft: targetOffset}, 400);
var timer = setTimeout(function() {
window.location.href = _this.hash; // '_this.hash' contains the anchor
}, 400);
return false;
You can also use window.location.hash like this:
window.location.hash = _this.hash;