Press "Enter" to skip to content

Angular Directive That Adds Sticky Position To An HTML Element

Angular ngx sticky Directive which adds a fixed position of an HTML element and also applies and removes a custom class when the element is fixed in position.

how to add and remove class in angular, angular add/remove class dynamically, add remove class onclick, add and remove class in javascript, onclick add and remove class to div

How to Create a Sticky Scrolling with jQuery Plugin | Jquery.smartSticky

How to make use of it:

Install ngx-sticky-directive:

# using npm
npm install ngx-sticky-directive --save

# using yarn
yarn add ngx-sticky-directive

Import the installed library:

import { StickyDirectiveModule } from 'ngx-sticky-directive';

@NgModule({
  ...
  imports: [
    ...
    StickyDirectiveModule
  ]
})
export class AppModule { }

Use it in your component.

@Component({
  selector: 'dummy-component',
  styles: [
    `
      .body-container {
        background-color: yellow;
        height: 2000px;
        overflow: scroll;
        padding: 10px;
      }

      .super-height {
        background-color: black;
        height: 5000px;
        position: relative;
        width: 100%;
      }

      #sticky-component {
        background-color: green;
        height: 50px;
        width: 100%;
        top: -10px;
        z-index: 10;
      }

      .when-sticky {
        background-color: magenta !important;
      }
    `,
  ],
  template: `
    <div class="body-container" #scCont>
      <div
        id="sticky-component"
        ngxSticky
        classWhenSticky="when-sticky"
        [triggerOn]="'trigger-on'"
        [scrollContainer]="scCont"
      ></div>
      <div id="trigger-on" class="super-height"></div>
    </div>
  `,
})
class DummyComponent {}

Properties

NameDescription
`@Input() scrollContainer: stringElementRef
`@Input() triggerOn: stringElementRef
@Input() debugMode: booleanDisplay or hide the sentinel element.
@Input() classWhenSticky: stringCSS class to be added to the target element when becomes sticky.
@Input() zIndex: number = 10CSS zIndex value to set to the target element. By default is 10.
@Input() top: number = 0CSS top value to set to the sticky element. By default is 0.

Add & Remove CSS Classes When Elements Is Sticky, ngx-sticky-directive Plugin/Github, add class using javascript, remove class using javascript


See Demo And Download

Official Website(bikecoders): Click Here

This superior jQuery/javascript plugin is developed by bikecoders. For extra advanced usage, please go to the official website.

Be First to Comment

    Leave a Reply

    Your email address will not be published.