Add a ‘Scroll to top of page’ Button

(by AXDS)

Thanks to: http://www.webtipblog.com/adding-scroll-top-button-website/


Example: https://jsfiddle.net/zgmnhLkL/

Checks for a scroll event past a threshold. Once triggered uses jQuery to toggle a class on the button. This class shows/hides the button using CSS. A click event is added to the button to scroll the window to a given element or id.

HTML:

<div style="height:3000px;border:1px solid black;">
<!-- Mimics the site content -->
</div>
<div class="scroll-top-wrapper ">
<span class="scroll-top-inner">
<i class="fa fa-2x fa-arrow-circle-up"></i>
</span>
</div>

JavaScript (jQuery):


$(function() {
$(document).on('scroll', function() {
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});

function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({
scrollTop: offsetTop
}, 500, 'linear');
}

CSS:


.scroll-top-wrapper {
position: fixed;
opacity: 0;
visibility: hidden;
overflow: hidden;
text-align: center;
z-index: 99999999;
background-color: #777777;
color: #eeeeee;
width: 50px;
height: 48px;
line-height: 48px;
right: 30px;
bottom: 30px;
padding-top: 2px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}

.scroll-top-wrapper:hover {
background-color: #888888;
}

.scroll-top-wrapper.show {
visibility: visible;
cursor: pointer;
opacity: 1.0;
}

.scroll-top-wrapper i.fa {
line-height: inherit;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s