I'm using the following code to smooth the movement when user clicks on a link that its href
starts with an "#"
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
I need to add about 40px to the scrollTop value, so the stopping point doe snot cover the content. I modified the code to this, but it does not seem to be doing it (notice the +40 towards end of the code):
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top + 40
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
I know a late answer but someone seeking a solution can try this.
By adding .top + (-40) will do the trick
$('html, body').stop().animate({
'scrollTop': $target.offset().top + (-40)
}, 900, 'swing', function () {
window.location.hash = target;
});
The +40
offset which you actually want to be a -40
is not working because once the animation is complete the browser is doing it's default reaction of going to the element with the id
you are passing to window.location.hash
You can either remove that line or add the following css to the elements being scrolled to.
padding-top: 40px;
margin-top: -40px;
See FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With