Table of Contents
1. Create the Button with HTML
2. Style the Button with CSS
3. Add JavaScript to Control Visibility and Scrolling
Optional: Use an Icon instead of Text
Home Web Front-end HTML Tutorial How to create a 'scroll to top' button with HTML

How to create a 'scroll to top' button with HTML

Aug 28, 2025 am 03:45 AM

Create an HTML button and set the click event to call the JavaScript function; 2. Use CSS to pin the button to the lower right corner of the page and set the hidden default state; 3. Listen to the scroll event through JavaScript, and display the button when the scroll distance exceeds 300px, and scroll smoothly to the top when clicked. Finally, a return to the top button to improve the user experience is realized, and the full functionality is completed in collaboration with HTML, CSS and JavaScript.

How to create a \

Adding a "scroll to top" button improves user experience by letting visitors quickly return to the top of a long webpage. Here's how to create one using HTML, CSS, and a bit of JavaScript.

How to create a

1. Create the Button with HTML

Start by adding a button element in your HTML. You can place it near the end of your content or in a fixed position.

 <button onclick="scrollToTop()" id="scrollBtn">Top</button>

This creates a simple button that calls a JavaScript function scrollToTop() when clicked.

How to create a

2. Style the Button with CSS

Use CSS to position the button (usually fixed in the bottom-right corner) and make it visually appealing.

 #scrollBtn {
  display: none; /* Hidden by default */
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 99;
  font-size: 18px;
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

#scrollBtn:hover {
  background-color: #0056b3;
}

The button is hidden initially ( display: none ) and will only appear when the user scrolls down a certain distance.

How to create a

3. Add JavaScript to Control Visibility and Scrolling

You need JavaScript to:

  • Show the button when the user scrolls down
  • Hide it when near the top
  • Smoothly scroll back to the top when clicked
 // Show/hide button based on scroll position
window.onscroll = function() {
  const btn = document.getElementById("scrollBtn");
  if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
    btn.style.display = "block";
  } else {
    btn.style.display = "none";
  }
};

// Scroll to top function
function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: &#39;smooth&#39;
  });
}

Note: document.documentElement.scrollTop is used for modern browsers, while document.body.scrollTop handles older ones.


Optional: Use an Icon instead of Text

You can replace the text "Top" with an upward arrow icon using Unicode or an icon library like Font Awesome:

 <button onclick="scrollToTop()" id="scrollBtn">↑</button>

Or with Font Awesome:

 <button onclick="scrollToTop()" id="scrollBtn">
  <i class="fas fa-arrow-up"></i>
</button>

(Just make sure to include the Font Awesome library in your HTML.)


That's it. With these three parts — HTML structure, CSS styling, and JavaScript logic — you have a fully functional scroll-to-top button. It's not complex, but small details like smooth scrolling and smart visibility make a big difference in usability.

The above is the detailed content of How to create a 'scroll to top' button with HTML. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Extract nested URLs from dynamic web pages using R language: httpr and API interaction practice Extract nested URLs from dynamic web pages using R language: httpr and API interaction practice Aug 27, 2025 pm 07:06 PM

This tutorial explores the problem of crawling failure if JavaScript dynamically loads content when crawling URLs from web pages using the R language rvest package. The article explains in detail why traditional HTML parsing methods may be invalid and provides an efficient solution: by identifying and directly calling the API interface behind the web page, using the httr package to obtain JSON data, thereby successfully extracting the required information.

How to disable a form element in HTML How to disable a form element in HTML Aug 30, 2025 am 08:45 AM

To disable HTML form elements, you can use the disabled attribute, which can prevent user interaction and the element value will not be submitted with the form. This attribute is of a Boolean type and can be directly added to form element tags such as input, textarea, select, or button. For example, it can also be dynamically controlled through JavaScript, such as document.getElementById("myInput").disabled=true. If the element cannot be edited but the value is still submitted, you should use the readonly attribute. The disabled attribute is simple and effective and widely supported.

How to link to a specific part of a page using anchors in HTML How to link to a specific part of a page using anchors in HTML Aug 31, 2025 am 06:52 AM

TolinktoaspecificpartofapageusinganchorsinHTML,assignauniqueidtothetargetelement,suchas,thencreateahyperlinkwithhref="#section1"toscrolltothatsection,andforcross-pagelinking,usethefullURLlikepage.html#section1,ensuringsmoothnavigationwithou

How to create a 'scroll to top' button with HTML How to create a 'scroll to top' button with HTML Aug 28, 2025 am 03:45 AM

Create an HTML button and set the click event to call the JavaScript function; 2. Use CSS to pin the button to the lower right corner of the page and set the hidden default state; 3. Listen to the scroll event through JavaScript, and display the button when the scroll distance exceeds 300px, and scroll smoothly to the top when clicked. Finally, a return to the top button to improve the user experience is realized, and the full functionality is completed in collaboration with HTML, CSS and JavaScript.

HTML form action and method attributes explained HTML form action and method attributes explained Aug 25, 2025 am 09:16 AM

Theactionattributespecifieswheretosendtheformdata,andthemethodattributedefineshowtosenditusingHTTPmethods.1.TheactionattributesetsthedestinationURL(absoluteorrelative);ifomitted,theformsubmitstothecurrentpage.2.Themethodattributeuses"get"to

CSS Custom Transparent Floating Scroller Tutorial CSS Custom Transparent Floating Scroller Tutorial Aug 28, 2025 pm 07:21 PM

This article details how to use CSS to achieve transparent and floating custom scroll bars on content. By combining overflow: overlay; attributes and scrollbar pseudo-element styles for different browsers (WebKit/Firefox), you can precisely control the color, transparency, width and rounded corners of scrollbars, thereby improving the visual consistency and user experience of the web interface.

How to restrict file types for an upload input in HTML How to restrict file types for an upload input in HTML Aug 24, 2025 am 02:57 AM

Use the accept attribute to limit the upload type of HTML file, such as accept="image/*" only allows images, accept=".pdf" only allows PDF, accept=".doc,.docx,.pdf,.txt" allows multiple specified types, and can combine JavaScript to verify file types to improve user experience, but security verification must be performed on the server side, because the accept attribute is not secure and the browser supports are different, and it is only used to improve availability rather than replace server verification.

How to make a non-breaking space in HTML How to make a non-breaking space in HTML Sep 01, 2025 am 07:40 AM

Use it to create line-breaking spaces in HTML, such as preventing the display of numbers and unit branches; 1. Used to avoid breaking lines between names, values ​​and units; 2. Maintain the text format within the line; 3. It can be used as a blank placeholder, but CSS is recommended; other space characters such as  ,  , etc. are suitable for special scenarios, but in most cases it is sufficient; be careful not to abuse the layout, CSS should be used instead, and multiple will not be merged, and the screen reader can recognize it normally, so it is necessary to use reasonably to ensure the text is displayed coherently.

See all articles