1
\$\begingroup\$

I have this JavaScript code that works as a top-of-page button when clicked. The button is hidden by default and only appears when the user scrolls 500px or more from the top of the page. But I am not that confident in this code as I am a beginner in JavaScript. Is there a shorter and more optimal way of doing it (excluding using the plain html anchor link <a href="#topButton">Top</a>):

var topBtn = document.getElementById("topButton");
var scrollExt = document.body.scrollTop;

window.onscroll = function() {
  ((document.body.scrollTop > 500 || document.documentElement.scrollTop > 500) ?
  topBtn.style.display = "block" : topBtn.style.display = "none");
};

topBtn.onclick = function() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}

CSS:

#topButton {display:none;position:fixed;bottom:50px;right:30px;z-index:99;padding:15px}

I have added this in the HTML as I have a difficult time creating the button using JavaScript:

<button id="topButton" title="Go to top">Top</button>
\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review. Here, we require the code to be working as intended before we can critique it. We cannot rewrite your code to add a fading feature. \$\endgroup\$ – 200_success Dec 8 '17 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.