Vanilla Back To Top
Configurable zero dependency Back To Top button that will work for 93.86% of all users worldwide
Ideal for pre-rendered static websites with no frameworks, e.g., Jekyll, Hugo or Hexo
Consider ★ starring if you like it!
How to use
Add this to your HTML:
<script src="https://unpkg.com/vanilla-back-to-top@4.0.3/dist/vanilla-back-to-top.min.js"></script>
<script>addBackToTop({})</script>
If you don't want to rely on unpkg.com, save the file to your project and serve it from your server:
<script src="/assets/vanilla-back-to-top.min.js"></script>
<script>addBackToTop({})</script>
There's also a UMD build available so you could import it in your asset pipepline:
npm install --save vanilla-back-to-top
import { addBackToTop } from 'vanilla-back-to-top'
addBackToTop({})
Optionally customise CSS of the button using #back-to-top
selector, e.g.:
#back-to-top a {
text-indent: -9999px;
background-image: url(back-to-top.png)
}
@media screen and (max-width: 479px) {
#back-to-top {
right: 10px;
bottom: 10px;
}
}
Options
addBackToTop
function accepts many options, e.g.:
addBackToTop({
id: 'back-to-top',
showWhenScrollTopIs: 300,
onClickScrollTo: 0,
innerElement: document.createTextNode('Up'),
size: 50,
fontSize: 14,
cornerOffset: 20,
backgroundColor: '#000',
textColor: '#fff',
zIndex: 1,
scrollContainer: document.documentElement
})
^ All these are also default values.
id
- id attribute of the buttonshowWhenScrollTopIs
- show the button when page got scrolled by this number of pixelsonClickScrollTo
- where to scroll to when the button gets clicked, 0
means the very topinnerElement
- DOM element to put inside the button; with jQuery you can put something like this: $('<svg>...</svg>').get(0)
size
- width and height of the button in pixelsfontSize
- font size of the text inside the buttoncornerOffset
- right and bottom offset of the button relative to viewportbackgroundColor
- background color of the buttontextColor
- text color of the buttonzIndex
- z-index of the buttonscrollContainer
- if only part of your website gets scrolled, e.g., when your sidebar never scrolls with content, put the scrolled DOM element here
Supported browsers
- Android Browser >=4.4
- Blackberry >=7
- Chrome >=4
- Chrome Android
- Edge >=12
- Explorer >=10
- Explorer Mobile >=10
- Firefox >=4
- Firefox Android
- iOS Safari & Chrome >=7.1
- Opera >=12.1
- Opera Mobile >=12.1
- Safari >=5.1
- Samsung Internet >=4
- UC Browser Android >=11.4
This gives 93.86% global coverage.
Limitations are due to flexbox and position:fixed.