Reputation: 1706
How can I modify this so that I can make it scroll to the class rather than an ID?
JS:
// Scroll To # Links
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 700, 'swing', function () {
window.location.hash = target;
});
});
HTML:
<a href="#test">test link</a>
<div class="test" style="margin-top: 1000px;">
testing content
</div>
Upvotes: 2
Views: 696
Reputation: 2180
try below code
// Scroll To # Links
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
var target = this.hash;
target = target.replace('#', '');
var $target = $('.' + target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 700, 'swing', function() {
window.location.hash = '#' + target;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#test">test link</a>
<div class="test" style="margin-top: 1000px;">
testing content
</div>
Upvotes: 0
Reputation: 82241
You can use the fetched value to get the classname and then target the element by class:
var target = this.hash;
var $target = $('.'+target.replace('#',''));
Upvotes: 1