Created
April 30, 2020 14:24
-
-
Save Farmatique/536f04b3ac905189a74228c262036435 to your computer and use it in GitHub Desktop.
Fixed button scroll to top appear on scrolling from top
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener('DOMContentLoaded', function() { | |
function throttle(fn, threshhold, scope) { | |
threshhold || (threshhold = 250); | |
var last, | |
deferTimer; | |
return function () { | |
var context = scope || this; | |
var now = +new Date, | |
args = arguments; | |
if (last && now < last + threshhold) { | |
// hold on to it | |
clearTimeout(deferTimer); | |
deferTimer = setTimeout(function () { | |
last = now; | |
fn.apply(context, args); | |
}, threshhold); | |
} else { | |
last = now; | |
fn.apply(context, args); | |
} | |
}; | |
} | |
function checkScrollPositionForButton(pos){ | |
if (pos>100){ | |
jQuery('#fixed-button-to-top').removeClass('hidden'); | |
} else { | |
jQuery('#fixed-button-to-top').addClass('hidden'); | |
} | |
} | |
checkScrollPositionForButton(jQuery(window).scrollTop()); | |
jQuery(window).scroll(throttle(function (event) { | |
checkScrollPositionForButton(jQuery(window).scrollTop()); | |
}, 150)); | |
jQuery('#fixed-button-to-top').on('click', function(e){ | |
e.preventDefault(); | |
window.scroll({ | |
top: 0, | |
left: 0, | |
behavior: 'smooth' | |
}); | |
}) | |
}) | |
<a href="#" id="fixed-button-to-top" style="border: 1px solid black;padding: 20px;position: fixed;z-index:1000;bottom:50px;right:0;">Scrolltop</a> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment