Determine the visibility of a text div for a user in Angular

After researching, I discovered a method to detect if the user has scrolled by using:

@HostListener("window:scroll", [])
onWindowScroll() {
    this.scrolled = window.scrollY > 0;
}

This implementation works effectively for triggering an animation on the first paragraph when the user scrolls "below-the-fold" (by adding a CSS class to a text division).

Now, my challenge is figuring out how to replicate this behavior for when a user scrolls past the "second" fold and enters the third. I aim to dynamically add the CSS class to display the text whenever it becomes visible to the user (once they have scrolled beyond a certain pixel threshold) and remove it when the text goes out of view as the user scrolls back up.

Can anyone provide guidance on achieving this functionality in TypeScript/Angular?

Answer №1

I utilized the solution provided in this response: Check if element is partially in viewport

  @ViewChild("targetDivId", {static: false}) private targetDiv: ElementRef<HTMLDivElement>;

  @HostListener('window:scroll', ['$event'])
  isScrolledIntoView(){
    const isElementXPercentInViewport = function(el: ElementRef, percentVisible=0.5) {
      // https://stackoverflow.com/questions/30943662/check-if-element-is-partially-in-viewport/51121566#51121566
      let
        rect = el.nativeElement.getBoundingClientRect(),
        windowHeight = (window.innerHeight || document.documentElement.clientHeight);
      return !(
        Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-rect.height) * 100)) < percentVisible ||
        Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
      )
    };

    if (this.targetDiv){
      this.scrolled = isElementXPercentInViewport(this.targetDiv);
    }

Extremely adaptable. I would definitely suggest using it.

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

Easily center list item numbers vertically within fixed height containers

I am facing an issue with the alignment of ordered list item numbers in a list with fixed height and vertically centered content. The numbers seem to be positioned inaccurately. li { height: 80px; border: 1px solid black; } li > span { heigh ...

Scroll on sidebar that overflows, rather than the page behind

My goal is to have a fixed background page while allowing the sidebar to scroll independently. Both elements are too large for the screen, so I want the page to scroll normally until the navbar overflows in height and becomes scrollable. Check out the exam ...

Can Phonegap be utilized to port a PlayN game to iOS?

PlayN seems like a fantastic tool for creating Html5 games. I'm curious to know if there are any plans to ensure that the html/javascript output is compatible with Phonegap, ultimately allowing for the creation of an iOS executable? ...

IE11 and how it handles Typescript and promises

Currently, I am utilizing Typescript version 2.4.2 along with Webpack for compilation purposes. Despite successful compilation, when running my code on IE11, an error 'Promise' is undefined arises. Below is a glimpse of my tsconfig: { "comp ...

Angular 5 - Performing Jasmine Testing: Simulating an Error Response on a Genuine HTTP Request

Before I start, I'd like to mention that I am currently in the process of learning Angular 4 as part of an internship. This is all very new to me. Anyway, I have a requirement where I need to simulate an error during an HTTP request in the controller ...

Stop specific HTML elements from displaying using Python

Let's consider a scenario where we have the following string: string = '<img src="image.png"><input type=text>' We also have a special function that converts the string into HTML markup, allowing only certain tags like <img& ...

What is the best way to declare this massive entity in typescript?

In the process of parsing a file, a large object is returned by the main function. function parse(file){ /* dostuff.. */ return myObject } The order of determining properties is crucial (e.g., "a" must be determined before "b" or the value will be differe ...

Linkage Transformation

Seeking a solution for managing dynamic links. Imagine having a basic link like this: <a href="~/Test/Test.pdf" target="_blank">Test Dynamic Links</a> If there is a button or input that allows users to replace that link with another, how can ...

Splitting a text string in PHP: Separating song titles from artist names

Here is a snippet of PHP code that retrieves artist and title information: <?php //get artist/title info $artist = $_GET['artist']; $title = $_GET['title']; //create a temp file to store values for AJAX script $r = fopen("temp_titl ...

The header and logo are missing from my webpage

I am facing an issue where my navigation bar is not displaying at the top of my screen, even though there are no syntax errors. Is there something in the syntax that needs to be adjusted? Or did I overlook something in my default template file? The webpage ...

What strategies can be used to prevent type errors in redux with Typescript?

As I navigate through my react-redux typescript project, I strive to steer clear of the "any" type. While still relatively new to typescript, I have grown quite fond of it. However, there remains a lingering question in my mind - where exactly sh ...

Executing function in component via template

Within the template section <tr *ngFor='let activity of pagedWorkflowActivities' [style.background-color]="setBackgroundColor(activity)"> In the component section setBackgroundColor(activity: WorkflowActivity) { return 'red&apos ...

unwelcome tab spacing in CSS

I am facing an issue with unwanted spacing in my lists. I have a code that generates three-column lists, each containing about eight rows. However, the first list item of the last row is causing an unwanted space. It seems to shift entirely to the next col ...

Using TypeScript to Initialize Arrays with Objects

Why is it that in TypeScript 1.8, the following code blocks with initializers are considered legal syntax: class A { public textField: string; } var instanceOfClass = new A { textField = "HELLO WORLD" }; var arrayCollection = new A[] { new A ...

``Please proceed with the form submission only if it has been verified and

Within my web application, there are several pages that handle submitted data from forms. I would like to prevent the following scenario: A user creates a form on the client side with identical fields to my original form and sends it to the URL responsibl ...

The state of XMLHttpRequest always remains in a perpetual state of progress, never

I have come across an MVC Core application. One of the methods in this application currently has the following structure: public IActionResult Call(string call) { Response.ContentType = "text/plain"; return Ok(call); } In addi ...

HTML code with embedded messages

I am interested in creating a straightforward message forum system. My goal is to organize messages in a nested structure (answering questions). For my website, I want it to be in Hebrew (dir="rtl"). I am considering generating <ol> elements dynam ...

Creating an Angular FormControl that can toggle multiple buttons

Here is the object I am currently working with currentApplication = { 'Initial': [12, 2, true, true, false], 'Reminder1': [8, 2, true, true, false], 'Reminder2': [4, 2, true, true, false], ...

Why should you use DIV comment tags in HTML code and how can you automate their implementation?

As I've been browsing through the codes of various professional websites, I couldn't help but notice how the HTML code is often neatly commented like this: <!-- END DIV Main Menu --> This type of commenting can be really beneficial, don&a ...

AgGrid Encounters Difficulty in Recovering Original Grid Information

After making an initial API call, I populate the grid with data. One of the fields that is editable is the Price cell. If I edit a Price cell and then click the Restore button, the original dataset is restored. However, if I edit a Price cell again, the ...