Is there a way to show an element on a website only when the height of the HTML content exceeds the height of the viewport?

My webpage serves as a dynamic to-do list, allowing users to add an endless number of tasks of all types. As the list grows in size, the page height increases and a scrollbar appears. Positioned at the bottom right corner of the page is a fixed button that simply takes users back to the top.

What I aim to achieve is to hide the button when the page height does not exceed the viewport height (preventing scrolling) as it would serve no purpose. On the other hand, once the page surpasses 100vh in height, I want the button to become visible by setting its display property to block.

Answer №1

To easily determine if the page content exceeds the viewport height and is scrolled, you can check the value of window.scrollY. If it is not equal to 0, it indicates that the page is scrolled, prompting you to display or hide a "back to top" button accordingly. Here's a simple 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;
}

Check out this fiddle to see the solution in action (adjust your window height for scroll behavior):

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


Create Smooth Scroll and Fade Effect for the Button

For an enhanced user experience, consider implementing a smooth scroll effect and fade in/out animation for the button instead of simply toggling display: none:

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

Answer №2

Although I haven't actually tried it out, I believe it's possible to achieve this using @media queries:

.topbutton {
    visibility: hidden;
}

@media screen and (min-height: 100vh) {
    .topbutton {
        visibility: visible;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

When trying to upload a file using multer, an error occurred stating "Unexpected field

My current issue involves using multer to upload an image from a form. However, I am encountering an Unexpected field error after uploading the image. In my HTML code, I have specified the file and file-model names as myFile. app.js var express = re ...

Reducing text size upon cell selection in Material UI Table

Seeking assistance in identifying the CSS property responsible for subtly shrinking text within cells when selected To see the issue, simply click on a cell in this code sandbox: https://codesandbox.io/s/material-ui-table-virtualized-t2xkt IMPORTANT: se ...

Is there a way to retrieve all div elements within a specific div using webdriver and selenium?

As a newcomer to the world of web scraping, I am currently working on scraping a website in order to extract all elements with the data-feature-id=homepage/story. My ultimate goal is to access a subelement within each of the divs contained in the parent el ...

Manipulating a 2D array in Javascript and Jquery: Implementing push functionality

I am trying to set up an array structure as follows: track[divID][wrapID] However, when I attempted track[divID][wrapID] = wrapID, I encountered an issue. This is because I need to add more elements to the second dimension in another loop, like this: tr ...

Discovered a critical vulnerability that requires your attention. Execute `npm audit fix` to resolve the issue, or use `npm audit` for more information

After attempting to install mysql using 'npm install mysql', I encountered an error message stating: "found 1 critical severity vulnerability run npm audit fix to fix them, or npm audit for details" Following this, I proceeded with 'npm au ...

Tricks for refreshing cached web page assets in the year 2023

So far, here are some of the old Cache Buster techniques I've come across: Adding a query string in the link src: /mstylesheet.css?cache_buster=12345 Changing the filename each time: /mstylesheet-12345.css Using Apache with Cache-Control "must-revali ...

The primary HTML file in Angular is unable to access the styles.scss file located in the src/styles directory

Just starting out with Angular. To incorporate the 7-1 scss pattern into my project, I established a styles folder within the src directory named "src/styles", and connected the components to the src/styles/style.scss file successfully. However, I'm ...

Transform the text upon hovering over the image, with the text positioned separate from the image

I'm looking for a solution where hovering over images in a grid area will change the text on the left side of the screen to display a predefined description of that image. I've been working on this problem for hours and would appreciate any help. ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

What are the steps to modify the authorization header of an HTTP GET request sent from a hyperlink <a href> element?

I have a unique Angular application that securely saves JWT tokens in localstorage for authentication purposes. Now, I am eager to explore how to extract this JWT token and embed it into an HTTP GET request that opens up as a fresh web page instead of disp ...

Prevent typing on input fields for numbers exceeding 3 digits

How can I prevent users from entering a number with more than 3 digits? For example, allowing entries like 150 but not accepting numbers like 1601. The keypress should be disabled in such cases. The keypress event must be disabled. <template> < ...

What is the best method for modifying an XML document without altering its associated XSL stylesheet?

I am working with XML data retrieved from a URL: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="/style.xsl"?> ....etc... To display the data in HTML format, I added the second line referencing the style.xsl file ...

Using CSS to rearrange the order of specific div elements with the nth-child() selector when targeting different

I am attempting to design a centered navbar for a webpage. The navbar consists of 5 divs and my goal is to have the third div become the first one when the screen size goes below 600px. Here is the HTML code: <div class="mainmenu"> < ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

Ensuring the accuracy of checkboxes in a loop through verification

How can I ensure that at least one checkbox is selected before allowing the user to move on to the next page using JavaScript with a form structure like this? echo "<form method=\"POST\" action=\"confirm.php\">"; $query = mysqli_ ...

Can Puppeteer extract the complete HTML content of a webpage, including any shadow roots?

When using Puppeteer to navigate a webpage, I typically can retrieve the full HTML content as text with this code: let htmlContent = await page.evaluate( () => document.querySelector('body').innerHTML ); However, I am currently faced with ...

Having trouble sending an array with res.send() in NodeJS

My User model contains a field that stores an array of course IDs like this: "courseId" : [ "5ac1fe64cfdda22c9c27f264", "5ac207d5794f2910a04cc9fa", "5ac207d5794f2910a04cc9fa" ] Here is how my routes are set up: router.get('/:userid/vendo ...

The combination of WASM and Node.js encounters an issue when attempting to utilize 'import.meta' outside of a module

I successfully compiled the FastText C++ module to a wasm module using the provided make file, with the following flags: EMCXX = em++ EMCXXFLAGS = --bind --std=c++11 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['addOnPos ...

Choose a selection from the options provided

This is a sample for demonstration purposes. I am trying to display an alert with the message "HI" when I click on Reports using the id main_menu_reports. My attempted solution is shown below. <ul class="nav" id='main_root_menu'> & ...