본문 바로가기
FRONT/JAVASCRIPT

scroll 이벤트 (jQuery 사용) 요소 일부가 보이면 토글클래스

by 홀로수키 2025. 6. 20.

[스크롤 이벤트 (jQuery코드임)]

 

● s-animation 클래스를 가진 요소가 뷰포트에 들어왔을 때 show 클래스를 토글
(요소가 스크롤로 화면 중간쯤에 들어오면 show 클래스 부여 / CSS 에서 show 클래스로 애니효과)

 

▷ 요소 선택 

const $sAnimations = $('.s-animation');

 

▷ 함수 작성

function scrollAnimation() {
  const triggerPoint = (window.innerHeight) / 1;

  $sAnimations.each(function(index, section) {
    const sectionTop = section.getBoundingClientRect().top - $(section).height() / 2;

    (sectionTop < triggerPoint)
      ? $(section).addClass('show')
      : $(section).removeClass('show');
  })
}

 

▷ 이벤트 바인딩

$(window).on('load', function() {
  $(window).on('scroll', scrollAnimation); // 스크롤할 때마다 실행
  $(window).on('resize', scrollAnimation); // 창 크기 바뀌어도 실행
  scrollAnimation(); // 초기 진입 시 실행
})

 

■ 코드 설명

▷ window.innerHeight → 현재 뷰포트 높이.
▷ / 1은 의미상 없어도 같음 (/1 = 원본 값).
▷ 즉, triggerPoint = 뷰포트 높이.
▷ .each 로 .s-animation 요소들을 반복.
▷ sectionTop = 현재 요소의 뷰포트 기준 top 위치 - 요소 높이의 절반
▷ getBoundingClientRect().top → 요소의 top 좌표 (뷰포트 기준)
▷ 이 값을 triggerPoint 와 비교: 요소의 상단이 트리거 지점보다 위에 있으면 .show 클래스 추가
▷ 아니면 .show 클래스 제거

 


[jQuery + IntersectionObserver 짬뽕]
**브라우저의 빌트인 옵저버 기능을 사용

■ 브라우저가 자동으로 요소가 뷰포트에 들어올 때 콜백 실행
■ 따로 scroll 감지 & 좌표계산 필요 없음
■ 성능 최적화

 

$(window).on('load', function() {
  const $sAnimations = $('.s-animation');

  // 브라우저 지원 여부 확인
  if ('IntersectionObserver' in window) {
    const observer = new IntersectionObserver(function(entries) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          $(entry.target).addClass('show');
        } else {
          $(entry.target).removeClass('show');
        }
      });
    }, {
      threshold: 0.5 // 50% 이상 보이면 실행
    });

    // 각 요소 등록
    $sAnimations.each(function() {
      observer.observe(this);
    });
  } else {
    // fallback: 지원 안되면 기존 스크롤 이벤트 사용
    function scrollAnimation() {
      const triggerPoint = window.innerHeight;
      $sAnimations.each(function() {
        const sectionTop = this.getBoundingClientRect().top - $(this).height() / 2;
        (sectionTop < triggerPoint) ? $(this).addClass('show') : $(this).removeClass('show');
      });
    }

    $(window).on('scroll resize', scrollAnimation);
    scrollAnimation();
  }
});

 

■ threshold ???

는 → IntersectionObserver 의 옵션 중 하나. 요소가 뷰포트에 어느 정도 보이면 콜백을 실행할지 정하는 값.

0: 요소가 조금이라도 보이면 트리거
0.5: 요소의 50%이상이 보이면
1: 요소가 완전히 다 보여야

 

 

'FRONT > JAVASCRIPT' 카테고리의 다른 글

이미지 태그에 alt 값 강제로 넣어주기.  (0) 2024.07.03