Back to top button visibility


Topic: Back to top button visibility
Published 02.08.2019 Updated 13.07.2019

vitticeps pro posted 3 weeks ago

A little directive can help to fade out the back to top button when the scroll bar hits the top (or when the page is loading at the first time..)


Usage:

Place the 'backToTopButton' attribute in the button tag.

<button backToTopButton class="btn btn-floating btn-large red waves-light animated d-none" mdbPageScroll [pageScrollDuration]="750" href="#top-section" mdbWavesEffect style="right:35px; bottom:35px;">
    <i class="fas fa-arrow-up"></i>
</button>


Create a back-to-top-button directive (back-to-top-button.directive.ts) with the following content -

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
	selector: '[backToTopButton]'
})

export class BackToTopButton {
	state = false;
	constructor( private btn: ElementRef, private renderer: Renderer2, ) { }

	@HostListener('window:scroll', ['$event'])
	checkScroll() {
		const scrollPosition = window.pageYOffset;

		if (scrollPosition < 200) {
			if (this.state) {
				if (this.btn.nativeElement.classList.contains("d-none")) {
					this.renderer.removeClass(this.btn.nativeElement, "d-none");
				}
				this.renderer.removeClass(this.btn.nativeElement, "fadeIn");
				this.renderer.addClass(this.btn.nativeElement, "fadeOut");
				this.state = false;
			}
		}
		else {
			if (!this.state) {
				if (this.btn.nativeElement.classList.contains("d-none")) {
					this.renderer.removeClass(this.btn.nativeElement, "d-none");
				}
				this.renderer.removeClass(this.btn.nativeElement, "fadeOut");
				this.renderer.addClass(this.btn.nativeElement, "fadeIn");
				this.state = true;
			}
		}
	}
}

Import it in your app.module.ts. Dont forget to place it in the declaration [] array.


Thanks for reading, hope it helped

Write
Please insert min. 20 characters.
Details of the article
  • Category: Angular
  • Specification: Angular