How to make to top using 5 lines of jQuery

Sometimes we find it hard to make a back to top button. And sometimes confused in many lines of code didn't understand what the error about is. Today we are going to make back to top functionality in 5 lines of jQuery.

GitHub:

GitHub logo nishthaneeraj / Back-to-top-in-jQuery

Simple Back to top Functionality Using jQuery

First, Make a footer with the id of footer or anything meaningfull

<footer class="page-footer  p-3 footer text-center" id="footer"> Back to Top

</footer>

Second, add some CSS (not compulsory but let's do it i have also added bootstrap in it
read this first

)

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap");

* {
  margin: 0;
  padding: 0;
}
body {
  background-color: #eec0c6;
  background-image: linear-gradient(315deg, #eec0c6 0%, #7ee8fa 74%);
  color: #002999;
  font-family: "Poppins", sans-serif;
  overflow-x: hidden;
}
html {
  scroll-behavior: smooth;
}
.footer {
  background: #002999;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
footer {
  margin: 0;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
}
/* Custom Scroll Bar */

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  background-color: #fff;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb {
  background-color: #00d9bf;
  border-radius: 5px;
}

Then, finally add JS
First add the jQuery link
( if you are using a code editor then add into the HTML file in the bottom after your script.js
jQuery Link: https://code.jquery.com/jquery-3.3.1.min.js
Or
If you are using codepen add in is section if you don't know read this post:

)

//Get the button:
const footer = document.getElementById("footer");

$("#footer").on("click", function () {
  $(window).scrollTop(0);
});

Explanation:
First Getting the Button

//Get the button:
const footer = document.getElementById("footer");

next adding Event Listener (Click Obviously) to it
then reseting the scroll value to 0

//Get the button:
$("#footer").on("click", function () {
  $(window).scrollTop(0);
});

That's it

Happy Coding πŸ˜ƒ.
Bye πŸ‘‹ have a good day 😊

23