Skip to content

Instantly share code, notes, and snippets.

@davidhellsing
Created January 17, 2018 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhellsing/6fbd8b82d14cec8482e9d9b427aae62c to your computer and use it in GitHub Desktop.
Save davidhellsing/6fbd8b82d14cec8482e9d9b427aae62c to your computer and use it in GitHub Desktop.
simple vanillaJS smooth scroll
<html>
<head>
<style>
#content{height: 8000px; width: 800px; margin: 0 auto; background: yellow;position: relative;}
</style>
</head>
<body>
<div id="content">
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
Lorem<br>
</div>
<script>
var pos = 0;
var value = 0;
var content = document.getElementById('content')
var contentHeight = 0
var windowHeight = 0
;(function loop() {
requestAnimationFrame(loop);
value += Math.round((pos-value)/4);
content.style.WebkitTransform = 'translate3d(0,-'+value+'px,0)'
})();
var onResize = function(e) {
windowHeight = window.innerHeight
contentHeight = content.offsetHeight
}
onResize()
var onWheel = function(e) {
e.preventDefault()
pos = Math.min(contentHeight-windowHeight, Math.max(0, pos+e.deltaY))
}
addEventListener('wheel', onWheel)
addEventListener('resize', onResize)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment