Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Easy Angular way to detect if element is in viewport on scroll

// the element that you are observing (just add #yourElement in the template) for this  query to work
    @ViewChild('yourElement') yourElement: ElementRef;

    ngAfterViewInit() {
        const threshold = 0.2; // how much % of the element is in view
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        // run your animation code here
                        observer.disconnect(); // disconnect if you want to stop observing else it will rerun every time its back in view. Just make sure you disconnect in ngOnDestroy instead
                    }
                });
            },
            { threshold }
        );
        observer.observe(this.yourElement.nativeElement);
    }
 
PREVIOUS NEXT
Tagged: #Easy #Angular #detect #element #viewport #scroll
ADD COMMENT
Topic
Name
7+7 =