Reputation: 21
I have some jquery for smooth scrolling:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1400);
});
Which works fine, except that I have some tabs on the page that use a hash link also. When you click each tab, the page scrolls to the top of the screen.
Is there a way to make this smooth scroll work, only when a specific anchor is added to the hash (like /#features) and not work when it is a hash only (like /#)
Upvotes: 2
Views: 1545
Reputation: 21672
You can add a :not()
selector to eliminate href="#"
from triggering your click
event.
$(document).on('click', 'a[href^="#"]:not([href=#])', function(event) {
console.log("Clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Hash Only</a>
<a href="#Anchor1">Anchor 1</a>
<a href="#Anchor2">Anchor 2</a>
Upvotes: 1