Reputation: 125
Struggling to implement a smooth scroll feature when navigating to an ID using my navbar. Instead, it makes the default jump, which is a bit of an eye sore.
I am very inexperienced using jQuery, so any pointers in the right direction would be much appreciated.
I have made an attempt to get this implemented however, as I have said, it is 'jumping' as opposed to scrolling.
HTML
<li>
<a href="#popular">Most Popular</a>
</li>
<div class="col-sm-12" id="popular">
<h3><i aria-hidden="true" class="fa fa-fire"></i> Most Popular</h3>
</div>
jQuery
$(document).ready(function() {
$("#popular").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('col-sm-12').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
});
}
Upvotes: 0
Views: 843
Reputation: 125
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
Add the above in your $(document).ready function in your jQuery file and all links which start with a # will have an animated scroll to the target.
Upvotes: 1
Reputation: 1355
Maybe try specifying the easing option.
Something like this:
$("#popular").click(function() {
$('html, body').animate({
scrollTop: $("#popular").offset().top
}, 800, 'linear');
});
Or:
$(document).ready(function () {
$("#popular").on('click', function (e) {
$('.col-sm-12').animate({
scrollTop: $(this).offset().top
}, 800);
});
});
Upvotes: 0