I am a beginner of jQuery. I have two functions on one page:
- which is a smooth scroll to id
- another that shows the back to the top element after the user scrolls a given distance.
Functions work independently, but when I combine them, as shown below, the "back to top" function does not work.
I think I missed something obvious and can use some help. Thank you
Update: This script shows the problem:
back to top jsfiddle
If the smooth scroll block is disabled, the back to top function works.
jQuery(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 -150}, 900, 'swing', function () {
window.location.hash = target;});
});
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('.go-top').fadeIn(200);
} else {
$('.go-top').fadeOut(200);
}
});
$('.go-top').click(function(event) {
event.preventDefault();
$('html, body').animate({scrollTop: 0}, 900);
});
});