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
Use the .animate()
function with scrollTop
like this:
function topFunction() {
$("html, body").animate({scrollTop: "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);
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.