Created
September 8, 2018 19:54
-
-
Save tysonchamp/c8971c723279c34e5f58647301d7cedb to your computer and use it in GitHub Desktop.
go to top jquery button
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<style> | |
body { | |
font-family: Arial, Helvetica, sans-serif; | |
font-size: 20px; | |
} | |
#myBtn { | |
display: none; | |
position: fixed; | |
bottom: 20px; | |
right: 30px; | |
z-index: 99; | |
font-size: 18px; | |
border: none; | |
outline: none; | |
background-color: red; | |
color: white; | |
cursor: pointer; | |
padding: 15px; | |
border-radius: 4px; | |
} | |
#myBtn:hover { | |
background-color: #555; | |
} | |
</style> | |
</head> | |
<body> | |
<a href="#top" id="myBtn" title="Go to top">Top</a> | |
<div style="background-color:black;color:white;padding:30px">Scroll Down</div> | |
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> | |
<script> | |
// When the user scrolls down 20px from the top of the document, show the button | |
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 | |
$("a[href='#top']").click(function() { | |
$("html, body").animate({ scrollTop: 0 }, "slow"); | |
return false; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment