Skip to content
Advertisement

How can I make an element visible on a page only when the html content height is bigger than the viewport height?

I have this page which is basically a to do list, where you can add an infinite number of tasks of every kind, and of course, if you add a lot of tasks the height of the page is going to get bigger, and the scollbar is going to appear. I also have this button fixed at the bottom right of the page, and its only function is to send you back to the top of the page. What I would like to do is to set the button’s display to none only in case the page height is not bigger than the viewport height (so it can’t scroll), because it would just be useless in this case, and then set its display to block in case the page has become higher than 100vh.

Advertisement

Answer

A simple way to do this is to check if the window.scrollY position value is 0. If not, you can assume that the page content is taller than the viewport and that the page is scrolled, so you can show/hide a “back to top” button accordingly. For example:

Javascript

window.addEventListener('scroll', () => {
  const toTopLink = document.getElementById('toTopLink');

  if (window.scrollY > 0) {
    toTopLink.classList.remove('hidden');
  } else {
    toTopLink.classList.add('hidden');
  }
});

HTML

<ul>
  <li>List Item</li>
  <li>List Item</li>
  <li>...</li>
</ul>

<a id="toTopLink" class="hidden" href="#">Scroll to Top</a>

CSS

#toTopLink {
  display: block;
  position: fixed;
  /* ... */
}

#toTopLink.hidden {
  display: none;
}

Here’s a fiddle showing this solution in action (note that you will need to resize your window height accordingly to see scroll behavior):

https://jsfiddle.net/dwq4h82x/8/


Smooth scroll and fade in/out of button

For some added goodness, you could do something like this instead of toggling display: none:

https://jsfiddle.net/6bjhvte4/3/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement