I wanted to make a button that goes to the top of the page but only appears when you're not at the top. There are probably libraries that already do this, but I wanted to make it myself and after some tinkering the following is what I came up with.
There is an occasional annoyance from quickly scrolling up & down with the mouse-wheel which causes jitters/unwanted permanence of the button @ top, but otherwise it works.
setInterval
is throttled in consideration for performance. I really get the feeling this could be improved, so I wondered if there is a more idiomatic/better way. What do you think?
var scrollVisible = false;
var userScrolled = false;
window.addEventListener('load', init, false);
function init() {
window.addEventListener('scroll', function() {
userScrolled = true;
}, false);
setInterval(function() {
if(userScrolled) {
if (window.pageYOffset == 0 && scrollVisible) {
document.getElementById("scrollbutton").style.visibility = 'hidden';
scrollVisible = false;
} else if (!scrollVisible) {
document.getElementById("scrollbutton").style.visibility = 'visible';
scrollVisible = true;
}
userScrolled = false;
}
}, 100);
}
function scrollUp() {
scrollTo(0, 0);
}
body {
background-color: #272822;
color: #F3F3F3;
}
#scrollbutton {
background-color: #666664;
border-radius: 100%;
position: fixed;
visibility: hidden;
font-size: 1.5em;
bottom: 0;
right: 0;
}
#scrollbutton:hover {
color: #A6E22E;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css"/>
<script src="test.js"></script>
</head>
<input type="button" value="⇧" id="scrollbutton" onclick="scrollUp();"/>
<body>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.
</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>
Contrary to popular belief, Lorem Ipsum is not simply random text.
It has roots in a piece of classical Latin literature.
</p>
</body>
<html>