Scroll top button|back to top Using HTML CSS & JQuery

Mar-05-2023 DevelopersTricks
Scroll top button|back to top Using HTML CSS & JQuery

Creating a “Scroll to Top” button is a great way to improve user experience on your website. With jQuery, you can easily add this functionality with a few simple steps.

First, you'll want to create the HTML element that will contain the “Scroll to Top” button. This can be a link, image, or any other HTML element. For this example, we'll use a link element.

Next, you'll need to add some CSS to style the element. For this example, we'll make the link look like a button with a round corner, a gray background, and white text.

.scroll-to-top {

background-color: #ccc;
padding: 10px;

border-radius: 50%;

color: #fff;

text-decoration: none;

}

 Now, it's time to add the jQuery code that will make the “Scroll to Top” button work. We'll bind the click event to the link element, and when the user clicks on it, the page will scroll to the top.

$(document).ready(function(){
	
	$('.scroll-to-top').on('click', function()

	{
		$('html, body').animate(

		{scrollTop : 0},800);
		return false;

	});

});

Finally, we'll add the code to show and hide the button, depending on the user's scroll position. When the user scrolls down the page, the button will appear and when the user scrolls to the top of the page, it will disappear.

$(window).scroll(function()

{
	
	if ($(this).scrollTop() > 100) 
	{

		('.scroll-to-top').fadeIn();

	} else 

	{

		$('.scroll-to-top').fadeOut();

	}
	
});

That's it! With these few steps, you can easily create a “Scroll to Top” button on your website with jQuery. This will make it easier for users to quickly jump to the top of the page with just one click.

Suggestions: Dear Programmers, I hope you understand the coding concepts discussed above. You can now easily embed the above functionality into your project. Please leave any comments or questions about this tutorial in the section below. You can also suggest web development-related topics.

Thank You for reading this tutorial...