I created a button with a link to go back to the top of the page.
Here is the JS code :
(function ($) {
/*--Scroll Back to Top Button Show--*/
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('#back-to-top').fadeIn();
} else {
$('#back-to-top').fadeOut();
}
});
//Click event scroll to top button jquery
$('#back-to-top').click(function(){
$('html, body').animate({scrollTop : 0},600);
return false;
});
})(jQuery);
Here is the HTML code:
<a id="back-to-top" href="#">
<i class="fas fa-chevron-circle-up fa-4x"></i>
</a>
It works very well, but I want to create a button instead of a link.
I tested the following HTML code but it does not work. There is the button but it does not go back up the page :
<button type="button" id="back-to-top" href="#">
<i class="fas fa-chevron-circle-up fa-4x"></i>
</button>
How to create a button to go back to the top of the page ?
It is same code for both. But notice if you didn't remove tag, than could happend that you have duplicate id and button will not work
(function ($) { /*--Scroll Back to Top Button Show--*/ $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('#back-to-top').fadeIn(); } else { $('#back-to-top').fadeOut(); } }); //Click event scroll to top button jquery $('#back-to-top').click(function(){ $('html, body').animate({scrollTop : 0},600); return false; }); })(jQuery);
body { min-height: 1000px; } button{ position: fixed; right: 5px; bottom: 10px; } a{ position: fixed; left: 5px; bottom: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="back-to-top" type="button"> Button </button>
The javascript to take you to the top of a page is...
window.scrollTo(0,0)
So when incorporated as a link, it will look like this...
<a href="javascript:window.scrollTo(0,0);">Go to top</a>
Or as a button, it will look like this...
<button onclick="window.scrollTo(0,0);">Go to top</button>
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.