TechSolutionsHere.com

How To Make A Scroll-to-Top Button?

scroll to top button

A Scroll-To-Top button to return to the top of the page allows users to go back to the top of the page without making too much effort. This can be very useful when a webpage has a lot of content or if it is a one-page website with plenty of materials. Besides, this button makes navigation easy on different sizes of mobile devices.

This Scroll-To-Top button helps quickly scroll through a page and also adds a more professional look to a website.

Step 1: HTML Code

<!-- Start Go Top Area -->
<div class="go-top">
	<i class="bx bx-chevrons-up"></i>
	<i class="bx bx-chevrons-up"></i>
</div>
<!-- End Go Top Area -->

Step 2: CSS Code

/*
Go Top Style*/ 
.go-top {
	position: fixed;
	cursor: pointer;
	top: 87%;
	right: -10%;
	background-color: $main-color;
	z-index: 4;
	width: 40px;
	text-align: center;
	height: 42px;
	line-height: 42px;
	opacity: 0;
	visibility: hidden;
	transition: .9s;
	i {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		left: 0;
		right: 0;
		margin: 0 auto;
		color: $white-color;
		transition: 0.5s;
		font-size: 20px;
		&:last-child {
			opacity: 0;
			visibility: hidden;
			top: 60%;
		}
	}
	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: -1;
		background-color: $main-color;
		opacity: 0;
		visibility: hidden;
		transition: 0.5s;
	}
	&:hover {
		color: $white-color;
		background-color: $main-color;
		&::before {
			opacity: 1;
			visibility: visible;
		}
		i {
			&:first-child {
				opacity: 0;
				top: 0;
				visibility: hidden;
			}
			&:last-child {
				opacity: 1;
				visibility: visible;
				top: 50%;
			}
		}
	}
	&:focus {
		color: $white-color;
		&::before {
			opacity: 1;
			visibility: visible;
		}
		i {
			&:first-child {
				opacity: 0;
				top: 0;
				visibility: hidden;
			}
			&:last-child {
				opacity: 1;
				visibility: visible;
				top: 50%;
			}
		}
	}
	&.active {
		transform: translateY(0);
		opacity: 1;
		visibility: visible;
		right: 3%;
		top: 87%;
	} 
}

Step 3: JS Code

// Go to Top
$(window).on('scroll', function(){
	var scrolled = $(window).scrollTop();
	if (scrolled > 300) $('.go-top').addClass('active');
	if (scrolled < 300) $('.go-top').removeClass('active');
});  

// Click Event
$('.go-top').on('click', function() {
	$("html, body").animate({ scrollTop: "0" },  500);
});

That’s it! Happy Coding 🙂

Exit mobile version