반응형
250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
Tags
- width
- For
- html
- insertAdjacentHTML
- css
- mousemove
- classList
- 애니메이션
- JavaScript
- addEventListener
- 반복문
- swiperjs
- scrollevent
- swiper
- 스크롤
- localstorage
- scroll
- scrollY
- Sticky
- Animation
- NodeList
- pointermove
- NAV
- Hover
- input
- 이벤트리스너
- React
- getBoundingClientRect
- forEach
- 확장성
Archives
- Today
- Total
ZeroToHunnit Coding
[Javascript] Intersection Observer로 애니메이션 만들기 본문
728x90
반응형
원래는 스크롤 이벤트로 이렇게 애니메이션을 만들었다면 이번에는 Intersection Observer로 간단한 애니메이션을 만들어보았다.
HTML
<div class="section">
<div class="box">
<p>안녕하세요?</p>
</div>
<div class="box">
<p>반갑습니다.</p>
</div>
<div class="box">
<p>스크롤 이벤트 말고</p>
</div>
<div class="box">
<p>intersection observer로</p>
</div>
<div class="box">
<p>조금 편하게 스크롤 애니메이션 줄 수 있어요</p>
</div>
<div class="box">
<p>대박이죠?</p>
</div>
</div>
CSS
.section{
height: 6000px;
}
.box{
margin-top: 800px;
}
.box p{
font-size: 60px;
font-weight: bold;
text-align: center;
opacity: 0;
transform: scale(0);
transition: all 0.6s;
}
.observe{
opacity: 1 !important;
transform: scale(1)!important;
}
미리 애니메이션을 넣어줄 클래스를 만들어두었다.
JAVASCRIPT
let observer = new IntersectionObserver(function(e){
e.forEach(function(a){
if(a.isIntersecting){
a.target.classList.add('observe');
} else{
a.target.classList.remove('observe');
}
})
},{
threshold: 0.5
});
for(let i = 0; i < document.querySelectorAll('.box p').length; i++){
observer.observe(document.querySelectorAll('.box p')[i])
}
우선 변수에 new IntersectionObserver(콜백함수, 옵션)을 담아준다. 그리고 변수.observe(찾을 요소)를 작성해주면 된다.
위의 의미는 observe로 특정 요소를 찾으면 변수에 있는 함수를 실행해준다는 의미다.
우선 IntersectionObserver의 콜백함수에 파라미터를 검사해보면 array로 데이터가 담겨있는 것을 볼 수 있기 때문에 forEach 반복문을 사용해주었다.
isIntersecting의 의미는 화면에 요소가 들어왔느냐를 체크해주는 boolean방식의 함수인데, 저렇게만 적어도 true, false가 출력되기 때문에 따로 등호를 안붙여줘도 된다.
그래서 true가 되면 클래스를 부여하고 false가 되면 클래스를 떼는 식으로 코드를 짰다.
threshold는 요소가 화면에 들어온 값을 백분율로 나타낸 것으로 0.5를 입력하면 50%가 화면에 나타나면 실행해라 라는 의미다.
검색해보면 IntersectionObserver로 무한 스크롤도 만들 수 있던데 생각보다 많은 작업들을 해낼 수 있을 것 같다.
728x90
반응형
'JAVASCRIPT' 카테고리의 다른 글
[Javascript] 확장성있게 모달창 띄우기 (0) | 2024.01.24 |
---|---|
[Javascript] 스크롤에 따라 박스 크기, 글자 크기, 위치 조정하기 (2) | 2024.01.22 |
[Javascript] 특정 섹션에 마우스 올리면 변하는 커서 (0) | 2024.01.19 |
[Javascript] 스크롤에 따라 한글자씩 나타나게 하기 (0) | 2024.01.18 |
[Javascript] 로컬스토리지로 하루 동안 안보이게 하는 팝업 만들기 (0) | 2024.01.17 |