Reputation: 527
I'm trying to add jQuery smooth scrolling, clicking the button gets me to the top of the page but the animation is not working.
jQuery(function( $ ){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 800) {
$('.fa-chevron-up').fadeIn();
} else {
$('.fa-chevron-up').fadeOut();
}
});
//Click event to scroll to top
$('.fa-chevron-up').click(function(){
$('html,body').animate({scrollTop : 0}, 800);
return false;
});
});
This is the button that appears when scrolling -
<a href="#" class="scrolltotop"><i class="fas fa-chevron-up"></i></a>
Tried jQuery(document) still no luck. Any ideas?
Upvotes: 0
Views: 266
Reputation: 16675
jQuery(function($) {
//Check to see if the window is top if not then display button
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('.scrolltotop').fadeIn();
} else {
$('.scrolltotop').fadeOut();
}
});
//Click event to scroll to top
$('.scrolltotop').click(function(e) {
$('html, body').animate({scrollTop : 0}, 800);
e.preventDefault();
});
});
a.scrolltotop {
bottom: 10px;
display: none;
position: fixed;
right: 10px;
}
html {
overflow-y: scroll;
}
div.content {
height: 400vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"> </div>
<a href="#" class="scrolltotop"><i class="fas fa-chevron-up"></i>^ Up</a>
The animation is not working because it is not being called. The reason the page scrolls back to the top is because you are effectively navigating to an undefined anchor (href="#"
).
Change this:
jQuery('.fa-chevron-up').click(function(){
To this:
jQuery('.scrolltotop').click(function() {
Since font-awesome icons generally work by assigning a character as a pseudo-element of the element the classes are applied to, it is possible that if you click directly on the icon, it might work as expected. In any case, you should apply the click handler to the a
tag element via the .scrolltotop
selector.
Note: I've also updated the selectors for the fade behavior.
Upvotes: 3