0

I already have a button in my html and css that appears when the user scrolls down 20px. When you click the button, it sends the user back to the top of the page. I would like it to animate scrolling back to the top, instead of jumping straight there. Here's my code:

HTML:

<button onclick="topFunction()" id="myBtn" title="Return To Top"><i class="fa fa-angle-up fa-lg"></i></button>

CSS:

#myBtn {
display: none; 
font-size: 2em;
position: fixed; 
bottom: 20px; 
right: 30px; 
z-index: 99; 
border: none; 
outline: none; 
background-color: rgba(0, 0, 0, 0.5); 
color: white; 
cursor: pointer; 
padding: 15px; 
border-radius: 10px; 
-webkit-transition: color 0.5s;
transition: color 0.5s;
}

#myBtn:hover {

color: #00ff0a;

}

Javascript:

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("myBtn").style.display = "block";
} else {
    document.getElementById("myBtn").style.display = "none";
}
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0; // For Chrome, Safari and Opera 
document.documentElement.scrollTop = 0; // For IE and Firefox
}

Any help is welcome

Noah Schmidt
  • 171
  • 1
  • 2
  • 6

2 Answers2

1

Use the .animate() function with scrollTop like this:

function topFunction() {
   $("html, body").animate({scrollTop: "0"});
}
Sudipto
  • 440
  • 2
  • 8
  • You can adjust the speed if you'd like as well. `$("html, body").animate({ scrollTop: 0 }, "slow");` or `$("html, body").animate({ scrollTop: 0 }, "fast");` or `$("html, body").animate({ scrollTop: 0 }, "1000");` . Default is 400ms. Manual: https://www.w3schools.com/jquery/eff_animate.asp – blackandorangecat Apr 02 '17 at 17:57
0

you could use the jQuery .animate() method, and the scrollTop property.

Example:

$(function(){
    $("#myBtn").click(function(e){
        e.preventDefault();
        $("html, body").animate({"scrollTop": "0px"}, 600);
    })
});
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126