A tutorial on implementing a "Back to Top" button that appears dynamically while scrolling in Angular

I've developed a scroll-to-top feature for my Angular project, but I'm facing an issue. The scroll icon appears immediately upon page load instead of only showing after the user scrolls down. Any ideas or suggestions on how to achieve this?

Here's what I'm aiming for:

  1. Hide the scroll icon when the page loads
  2. Show the scroll icon only when the user scrolls down

HTML

<div class="to-top" (click)="scrollToTop()" [ngClass]="{ 'show-scrollTop': windowScrolled }">
  <img src="../../../../assets/marketing-site/ecosystem/Scroll-to-Top.svg" alt="to-top-icon" />
</div>

CSS

.to-top {
  bottom: 0;
  cursor: pointer;
  margin: 0 8px 12px 0;
  position: fixed;
  right: 0;
}

.show-scrollTop {
  opacity: 1;
  transition: all 0.2s ease-in-out;
}

TS

  scrollToTop(): void {
    // scroll to the top of the body
    return this.document.body.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
      inline: 'start',
    });
  }

Check out the example I created here

Answer №1

HTML

.scroll-top {
  bottom: 0;
  cursor: pointer;
  margin: 0 8px 12px 0;
  position: fixed;
  right: 0;
  opacity: 0;
}

.show-scrollTop {
  opacity: 1 !important;
  transition: all 0.3s ease-in-out;
}

JavaScript

windowScrolled = false;

onInit() {
  window.addEventListener('scroll', () => {
    this.windowScrolled = window.pageYOffset !== 0;
  });
}

This solution should work perfectly.

Additionally, for smooth scrolling I recommend:

scrollToTop(): void {
  window.scrollTo(0, 0);
}

Answer №2

Your provided expression

if (window.pageXOffset || document.documentElement.scrollTo || document.body.scrollTop > 20) {
      this.windowScrolled = true;
} 

appears to be always evaluating to true. To improve readability and functionality, consider revising it to something like:

if( window.pageXOffset > 20 || document.body.scrollTop > 20) {}

Note that

document.documentElement.scrollTo
is a function and may not be used in the condition as intended.

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

Fieldset containing a table with a horizontal scrollbar

One issue I encountered in my application was dealing with a fieldset that contained table data with potentially many columns. To prevent the browser window from acquiring a horizontal scroll bar due to the wide table, I attempted to wrap the table in a c ...

Working towards ensuring my website is responsive

Hello, I am a CSS beginner currently working as an intern. My task is to make a website's CSS compatible with Internet Explorer, and then make it responsive and scalable. Essentially, the design should retain its appearance when the window size change ...

ASP.NET Core MVC: Issue with Passing C# Razor Variable to HTML Tag

GitHub Repo: https://github.com/shadowwolf123987/Gun-Identification-App I'm currently facing an issue in passing the values of two C# variables from the code block defined in my view to the corresponding html tags within the same view. Unfortunately, ...

Creating a Stylish ExtJS Container with CSS: A Step-By-Step

I've been experimenting with the ExtJS properties cls, bodyCls, and componentCls but unfortunately, I'm not achieving the desired outcome. As an illustration: Ext.create('Ext.form.Panel', { renderTo: document.body, title: &apo ...

Social media comments widget

Currently, I am incorporating the Facebook XML to implement a Facebook comments plugin within my MVC 3 application in the following manner: <fb:comments href="@Request.Url.AbsoluteUri" num_posts="15" width="900"></fb:comments> The issue lies ...

In my attempt to assess the correlation between value 1 and a value in the preceding object, I am utilizing the *ngFor directive

Attempting to compare 2 entries in an *ngFor loop. The code should compare the value at the current object to a value at the previous object. <ng-container *ngFor="let item of s_1.comments[0]; index as b"> <article class="message i ...

Tips on eliminating the background of a div nested within another div

<div class="white"> <div class="transparent"> ---- </div> <div class="content"> ---- </div> </div> I am working with a parent div .white that has a white background color. Inside this parent div, there are mul ...

When attempting to load a CSS file, Java automatically redirects to the login page

EDIT** After successfully loading CSS, I encountered an issue where the page kept redirecting back to login.jsp instead of displaying the CSS. Any insights on what might be causing this?https://i.sstatic.net/Ij7Oh.png I attempted to incorporate a custom ...

What is the method to prevent scrolling on the body while allowing scrolling on a specific div element?

<html> <body> <div class="container"> <div class="menu"></div> <div class="list"></div> </div> </body> </html> .menu{ float:left; width:50%; } .list{ float:right; width:50% ...

Using line breaks and horizontal scrolling in HTML and CSS

I am struggling with a div that contains multiple small spans. My goal is to implement a horizontal scrollbar that extends up until the line break tags (a-z on each line) in order to view the full content on narrow screens. Although I have applied the &ap ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Utilize swipe gestures in tables with Angular and Ionic for enhanced user interaction

I'm working on creating a swiping functionality for table pagination. Swiping right will take you to the next page, while swiping left will move you back to the previous page. Here's the code snippet of my table: <table #tableElement id=&qu ...

Styling <Link> component with styled-components: A step-by-step guide

Utilizing the Link component from @material-ui/core/Link in my TypeScript code was initially successful: <Link href="#" variant="body2"> Forgot? </Link> However, I am exploring the transition to styled-components located in a separate file. ...

creating a live updating dropdown menu using Node.js and MySQL

Upon a user clicking and selecting a client, I would like to dynamically update the region dropdown menu with options that are related to that specific client from the databaseenter code here This is my client table: Here is the Region table, where clien ...

Is there a way to only refresh the div specifically for the calendar with an id of "

$(document).ready(function() { $("#client-list").on("change", function() { var selectedValue = $(this).val(); location.reload(); }); }); Is there a way to refresh only the div with id='calendar' without refreshing the entire pa ...

Leveraging Angular 2 and Typescript for crafting a cutting-edge Chrome application

I am currently working on developing a Chrome App using the Angular 2 5-minute quick start as a reference to create a sample application. However, I have encountered security concerns related to how system JS functions with Chrome applications. Has anyone ...

drop down menu in navigation bar: unable to display items

I am having trouble with a dropdown menu in my code. Even though I used the code from the official Bootstrap website, the items are not appearing in the dropdown list. <nav class="navbar navbar-expand-lg navbar-dark bg-primary "> ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

Challenge with collapsing a button within a Bootstrap panel

Check out this snippet of code: <div class="panel panel-default"> <div class="panel-heading clearfix" role="tab" id="heading-details" data-toggle="collapse" data-target="#details" data-parent="#panel-group" href="#details"> <h4 c ...