0.1.3 • Published 6 years ago

@simcoder/ngx-scroll-tracker v0.1.3

Weekly downloads
1
License
MIT
Repository
github
Last release
6 years ago

ngx-scroll-tracker

Track any element to enhance scroll-based features in you app. Works for Angular 6+, both AoT and SSR.

Installation

$ npm install @simcoder/ngx-scroll-tracker

Usage

1. Import the Angular Module

import { NgModule } from '@angular/core';
import { ScrollTrackerModule } from '@simcoder/ngx-scroll-tracker';

@NgModule({
  imports: [
    ...
    ScrollTrackerModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. Apply Angular Directive

...
<div (scrollTracker)="handler($event)">
  <h1>Lorem Ipsum</h1>
  <p>Dolor sit amet</p>
</div>

3. Handle Scroll Tracker Events

import { Component } from '@angular/core';
import { ScrollTrackerEventData } from '@simcoder/ngx-scroll-tracker';

@Component({})
export class MyComponent {

  public handler(eventData: ScrollTrackerEventData) {
    // Use the eventData!
  }
}

Data API

The ScrollTrackerEventData interface defines the data being emitted from the tracker. First-level properties:

PropertyDescription
$eventNative Browser Event
elementRefAngular ElementRef to tracked Element
dataThe scroll data for the Element

The data property holds the following properties:

PropertyDescription
elementTop.fromContainerTopDistance between the top of the tracked element and the top of its scrollable container (pixels and ratio)
elementTop.fromContainerBottomDistance between the top of the tracked element and the bottom of its scrollable container (pixels and ratio)
elementBottom.fromContainerTopDistance between the bottom of the tracked element and the top of its scrollable container (pixels and ratio)
elementBottom.fromContainerBottomDistance between the bottom of the tracked element and the bottom of its scrollable container (pixels and ratio)

Notes

  • Negative values for both pixels and ratio means the element has scrolled past its contianer treshold (.fromContainerTop etc.).
  • Positive values for both pixels and ratio means the element has not yet reached its container tresheld.

Example

import { Component } from '@angular/core';
import { ScrollTrackerEventData } from '@simcoder/ngx-scroll-tracker';

@Component({})
export class MyComponent {

  public handler(eventData: ScrollTrackerEventData) {

    if (eventData.data.elementTop.fromContainerTop.ratio < 0) {
      console.log('Element Top is past Containter Top');
    }
    if (eventData.data.elementBottom.fromContainerBottom.ratio < 0) {
      console.log('Element Bottom is past Containter Bottom');
    }
    if (eventData.data.elementTop.fromContainerTop.pixels < 200) {
      console.log('Element Top is 200px from Containter Top');
    }
    if (eventData.data.elementTop.fromContainerTop.ratio > 0.25) {
      console.log('Element Top is past Containter Top');
    }

  }
}

License

MIT