'Javascript smooth scroll retain hash
I'm doing a smooth scroll on my page. But the problem is the hash link is removed when I smooth scroll directly to its target section. I need to keep the hash when smooth scrolling to the page. Does anybody know how to do this?
Here is my code
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
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) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
var $target = $(target);
$target.focus();
if ($target.is(":focus")) {
return false;
} else {
$target.attr('tabindex','-1');
$target.focus();
};
});
}
}
});
<div class="btn-container">
<ul>
<li class="tab-btn"><a class="smoothScroll" href="#stay">Stay</a></li>
|
<li class="tab-btn"><a class="smoothScroll" href="#travel">Travel</a></li>
|
<li class="tab-btn"><a class="smoothScroll" href="#promo">Promo</a></li>
</ul>
</div>
<div class="content-wrap" id="stay">
<p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Amet accusantium nam aliquam temporibus perspiciatis reiciendis mollitia magni, soluta commodi debitis, culpa porro quibusdam iure harum totam. Itaque, reiciendis. Nisi, fugiat. </p>
</div>
<div class="content-wrap" id="travel">
<p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Amet accusantium nam aliquam temporibus perspiciatis reiciendis mollitia magni, soluta commodi debitis, culpa porro quibusdam iure harum totam. Itaque, reiciendis. Nisi, fugiat. </p>
</div>
<div class="content-wrap" id="promo">
<p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Amet accusantium nam aliquam temporibus perspiciatis reiciendis mollitia magni, soluta commodi debitis, culpa porro quibusdam iure harum totam. Itaque, reiciendis. Nisi, fugiat. </p>
</div>
Solution 1:[1]
Try this script:
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function (event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function () {
window.location.hash = hash;
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
