Skip to content

Instantly share code, notes, and snippets.

@nateplusplus
Created December 8, 2015 16:00
Show Gist options
  • Save nateplusplus/5b8db15452945e7b8d52 to your computer and use it in GitHub Desktop.
Save nateplusplus/5b8db15452945e7b8d52 to your computer and use it in GitHub Desktop.
A little script I wrote for a pop-up button that scrolls users to top of page.
#to-top {
text-decoration: none;
color: white;
transition: color 0.15s ease, transform 0.5s ease;
position: fixed;
bottom: 2em;
right: 2em;
text-align: center;
padding: 0 0.5em;
}
#to-top:hover {
border-radius: 5px;
color: #9cc2de;
}
.hide-down {
transform: translateY(100px);
}
<!-- Make sure font awesome is included in header -->
<a href="#top"><!-- This marks point to scroll to: put directly under opening body tag -->
<!-- to-top button markup -->
<div id="to-top">
<i class="fa fa-chevron-up fa-3x"></i>
<p>To Top</p>
</div>
var toggleMenus = function (element, classSelector) {
// If the page is scrolled to top, hide the button with animation
if (pageYOffset <= 300 && !element.classList.contains(classSelector)) {
element.classList.add(classSelector);
}
// If the page is scrolled below 300px, unhide the button with animation
if (pageYOffset > 300 && element.classList.contains(classSelector)) {
element.classList.remove(classSelector);
}
}
document.addEventListener("DOMContentLoaded", function (event) {
var toTop = document.getElementById('to-top');
// Initial Load...
toggleMenus(toTop, 'hide-down');
// On Scroll...
window.addEventListener('scroll', function () {
toggleMenus(toTop, 'hide-down');
}, true);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment