Reputation: 740
I have smooth scroll JS to link from a menu item to an anchor further down the page.
The problem is that since I have tabs used on my page (which use #tabname) to navigate, it tries to scroll when using them as well.
Is there an easy change I can make to the JS to prevent this from working on tabs?
$(document).ready(function () {
// Add smooth scrolling to all links
$("a").on('click', function (event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
Upvotes: 1
Views: 769
Reputation: 7063
You could provide a way for anchor elements to opt out of the scroll behaviour, e.g. filter out anchors with a data-no-scroll
attribute:
<a href="#tab1" data-no-scroll>Tab1</a>
$("a").not("[data-no-scroll]").click(function() {
...
});
Upvotes: 3