×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: PHP
Posted by: david Panter
Added: Sep 11, 2019 10:19 AM
Views: 4066
Tags: no tags
  1. Create a button that will take the user to the top of the page when clicked on:
  2.  
  3. Example
  4. <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
  5. Step 2) Add CSS:
  6. Style the button:
  7.  
  8. Example
  9. #myBtn {
  10.  display: none; /* Hidden by default */
  11.   position: fixed; /* Fixed/sticky position */
  12.   bottom: 20px; /* Place the button at the bottom of the page */
  13.   right: 30px; /* Place the button 30px from the right */
  14.   z-index: 99; /* Make sure it does not overlap */
  15.   border: none; /* Remove borders */
  16.   outline: none; /* Remove outline */
  17.   background-color: red; /* Set a background color */
  18.   color: white; /* Text color */
  19.   cursor: pointer; /* Add a mouse pointer on hover */
  20.   padding: 15px; /* Some padding */
  21.   border-radius: 10px; /* Rounded corners */
  22.   font-size: 18px; /* Increase font size */
  23. }
  24.  
  25. #myBtn:hover {
  26.  background-color: #555; /* Add a dark-grey background on hover */
  27. }
  28.  
  29. Step 3) Add JavaScript:
  30. Example
  31. //Get the button:
  32. mybutton = document.getElementById("myBtn");
  33.  
  34. // When the user scrolls down 20px from the top of the document, show the button
  35. window.onscroll = function() {scrollFunction()};
  36.  
  37. function scrollFunction() {
  38.   if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
  39.     mybutton.style.display = "block";
  40.   } else {
  41.     mybutton.style.display = "none";
  42.   }
  43. }
  44.  
  45. // When the user clicks on the button, scroll to the top of the document
  46. function topFunction() {
  47.   document.body.scrollTop = 0; // For Safari
  48.   document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
  49. }