Animated scrolling in Angular

I am working on a webpage using Angular, where each module is a component with an animation. However, I am facing an issue where the animation only runs when the page loads, but I want it to happen while the component is visible on the screen. One approach I tried was to hide and show the component based on the scroll position of the page. Is there a better way to achieve this functionality?

@HostListener('window:scroll', ['$event']) onWindowScroll(e: any) {
  if (window.pageYOffset < 180) {
    this.heroShown = 0;
  } else {
    this.heroShown = 1;
  }
  console.log(e.target['scrollingElement'].scrollTop);
  console.log(document.body.scrollTop);
  console.log(window.pageYOffset);
}

Answer №1

If you want to achieve this effect, consider implementing an Intersection Observer. This observer triggers an event when the element becomes visible on the screen, allowing you to trigger your animation at that moment.

private createObserver() {
    const options = {
      rootMargin: '0px',
      threshold: this.threshold,
    };

    const isIntersecting = (entry: IntersectionObserverEntry) =>
      entry.isIntersecting || entry.intersectionRatio > 0;

    this.observer = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (isIntersecting(entry)) {
          this.subject$.next({ entry, observer });
        }
      });
    }, options);
  }

Alternatively, you can also utilize a library like gsap which provides features like scrolltrigger for achieving similar effects. Refer to their documentation here.

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

What is causing the input tag and button tag to appear on separate lines instead of together?

Here is my HTML and CSS code: <!DOCTYPE html> <html> <head> <title>assignment1</title> <meta charset="utf-8"> <meta name = "description" content="assignment"> <meta name = "keywords" content="php, assignm ...

Is there a way to extend a div to occupy two rows?

I am attempting to accomplish the following task: Here is my markup: <div> <div>A</div> <div>B</div> <div>C</div> </div> Can this be achieved using grid, bootstrap, or flex without altering the or ...

No translation or compiling of SCSS/SASS to CSS available

As a beginner Sass user, I am working on mastering the SMACSS hierarchy and incorporating it into my project using Brackets. However, I have encountered an issue with mapping the main.scss file to the main.css file even though it compiles successfully via ...

Allow only specific inner divs to dictate the width of the outer div

I'm working with the following HTML structure: <div id="container"> <div id="block1"> <img src="someimage/path" /> </div> <div id="block2"> Some Text </div> <div id="block3"&g ...

Implementing Service Communication

I created an Angular Application using the Visual Studio Template. The structure of the application is as follows: /Clientapp ./app/app.module.shared.ts ./app/app.module.client.ts ./app/app.module.server.ts ./components/* ./services/person-data.service. ...

Understanding the behavior of CSS float (even after thorough examination of W3C documentation)

I am currently facing an issue related to the float property and have provided a snippet of code below for reference. My goal is to achieve a two-column layout using floats. While I am familiar with other methods to achieve this layout, I am specifically i ...

Shine a light on the input with a captivating outer

Can we replicate the outer glow effect that Safari and other browsers automatically add to an input field without using jQuery? If you want to remove it, check out this article: Thank you! ...

Customizing the styling of an anchor tag using CSS in Bootstrap

I want my active link to appear red: nav class="navbar navbar-inverse"> <div class="container col-1 col-sm-12"> <ul class="nav"> <li class="<%= 'active' if current_page?(squad_path) %> ...

One way to ensure a necessary check on the mat-expansion-panel

Currently, I am working on a form that includes an upload panel (mat-expansion-panel) for uploading documents. My goal is to indicate that this panel is required by adding an asterisk (*) next to it. While I know how to add the asterisk to <textarea&g ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

There appears to be an issue with the indexes of the PointCloud

After setting up a point cloud and attempting to change vertex colors upon clicking a point, I encountered some issues. Despite working out the vertex colors and necessary indices, the colors do not change as expected. The index values also seem confusing ...

JavaScript Event Listener causing the Sticky Position to Break

I am currently dealing with a situation where I want to create a slide-in side menu that remains sticky. However, when I apply the position: sticky CSS property to my menu container, it causes the entire menu to be displayed (instead of being pushed off th ...

How to prevent npm from being accessed through the command prompt

I recently began working on a ReactJs project. However, I am facing an issue where after starting npm in Command Prompt, I am unable to enter any text. Should I close the cmd window or is there a way to stop npm? You can now access your project at the fol ...

Guide to placing an element behind text using Bootstrap 3

On my webpage, I have a straightforward Bootstrap Jumbotron displayed prominently: <div class="jumbotron"> <div class="container"> <h1>Welcome to My Wonderful Site</h1> <p>There's some information her ...

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

Configuring the space beneath a multi-line text with a bottom border distance or shadow

I am looking to add a bottom border with less spacing than default for specific text, creating a look similar to this image: Unfortunately, it seems the border property cannot achieve this effect. I am experimenting with the :after property to see if it c ...

Select a division and retrieve the identification of a different division

I am looking to trigger an event by clicking on one element and extracting the ID from a separate, unrelated div. Here is my attempt: $(".map_flag").on("click",function(){ var selectedID = ($(this).attr("data_modal")); $("#" + selectedID).fade ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

When I incorporate the h-100 class, my content expands beyond the container on mobile devices

Struggling with implementing bootstrap 4.0? I'm attempting to utilize h-100 to ensure that the background stretches to the bottom of the user's screen. I've experimented with clearfix, fluid-containers, and more in an effort to make it work ...

After filling out the form, the user's entered information is instantly shown on the same page

I want to create a form where my friend can input information that will be displayed on the same page. For example, when he enters the title in a text field and clicks submit, it should appear in the title box. Additionally, he should be able to enter va ...