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:
nishthaneeraj / Back-to-top-in-jQuery
Simple Back to top Functionality Using jQuery
Live Demo: https://nishthaneeraj.github.io/Back-to-top-in-jQuery/
Codepen:
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
How To use libraries and framework in Codepen
Nishtha Neeraj Kushwah ・ Jul 2 ・ 2 min read
)
@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:
How To use libraries and framework in Codepen
Nishtha Neeraj Kushwah ・ Jul 2 ・ 2 min read
)
//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 😊
Top comments (4)
Why use jQuery when there is a pure CSS solution ?
if you need smooth scroll
I know this but I'm not satisfied with this because when I use this it adds a #idname in the url but in my solution it's not adding anything in my url
Then this is a single line PURE JS solution :D
Thanks I don't know that thanks for this kind information