Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Created August 5, 2017 18:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save codediodeio/431a9ce4e37182b2c54548d9068deb72 to your computer and use it in GitHub Desktop.
Save codediodeio/431a9ce4e37182b2c54548d9068deb72 to your computer and use it in GitHub Desktop.
Animate a div based on scroll position Angular 4.3
<div class="box" [@scrollAnimation]="state">
<img src="https://images.pexels.com/photos/37547/suit-business-man-business-man-37547.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb">
</div>
import { Component, HostListener, ElementRef } from '@angular/core';
import {
trigger,
state,
style,
animate,
transition
} from '@angular/animations';
@Component({
selector: 'content-box',
templateUrl: './content-box.component.html',
styleUrls: ['./content-box.component.scss'],
animations: [
trigger('scrollAnimation', [
state('show', style({
opacity: 1,
transform: "translateX(0)"
})),
state('hide', style({
opacity: 0,
transform: "translateX(-100%)"
})),
transition('show => hide', animate('700ms ease-out')),
transition('hide => show', animate('700ms ease-in'))
])
]
})
export class ContentBoxComponent {
state = 'hide'
constructor(public el: ElementRef) { }
@HostListener('window:scroll', ['$event'])
checkScroll() {
const componentPosition = this.el.nativeElement.offsetTop
const scrollPosition = window.pageYOffset
if (scrollPosition >= componentPosition) {
this.state = 'show'
} else {
this.state = 'hide'
}
}
}
<div>
A whole bunch of text......
</div>
<content-box></content-box>
@javid-abd
Copy link

a good approach, but for only one div that needs to be animated. If you have multiple div elements, you won't be able to animate as scrolling down

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment