ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스크롤 하면 섹션에 따라 nav 메뉴가 활성화 되도록
    공부공부 2022. 1. 19. 00:12
    const boxes = document.querySelectorAll('.box');
          const options = {
            root: document.querySelector('.container'),
            rootMargin: '0px',
            threshold: 0.2
          }
    
          const callback = (entries, observer) => {
            entries.forEach(entry => {
              if(entry.isIntersecting){
                entry.target.classList.add('active');
              }else{
                entry.target.classList.remove('active');
              }
            })
          };
    
          const observer = new IntersectionObserver(callback, options);
          boxes.forEach(box => observer.observe(box));

     

    1. 모든 섹션 요소들과 메뉴 아이템들을 가져온다.

    ** 배열을 돌면서 각각의 아이디를 섹션 돔 요소로 변환하는 것 : map

       -> sectionIds 배열을 만들고 이걸 map을 통해 돔요소로 복사하여 만든다.

       -> 그럼 화면을 움직이면서 section을 찾을 때, navItems에서 동일한 것을 찾으면 된다.

    const sectionIds = [
        '#home',
        '#about',
        '#skills',
        '#work',
        '#contact'
    ];    
    
    const sections = sectionIds.map(id => document.querySelector(id));
    const navItems = sectionIds.map(id => document.querySelector(`[data-link="${id}"]`));
    
    const observerOptions = {
        root: null,
        rootMargin: '0px',
        threshold: 0.3,
    }
    
    const observerCallback = (entries, observer) => {
        entries.forEach(entry => {
            if(!entry.isIntersecting){
                const index = sectionIds.indexOf(`#${entry.target.id}`);
                
                
            }else{
                console.error(entry.target.id);
            }
        })
    };

     

    2. IntersectionObserver를 이용해서 모든 섹션들을 관찰한다.

    3. 보여지는 섹션에 해당하는 메뉴 아이템을 활성화 시킨다.

       -> 화면을 처음 띄웠을 때 work가 활성화되는 이유?

           콘솔창에 entry를 출력하면 일부 섹션의 콜백함수가 호출된 것을 확인할 수 있다.

           그걸 다시 뜯어보면 intersectionRatio가 0인 상태로 나온다.

           -> 페이지를 띄우자 마자 해당 섹션들은 화면 밖으로 나가 있어서 볼 수 없다.

            MDN 사이트에서 정의한 intersectionRatio

    The degree of intersection between the target element and its root is the intersection ratio
    . This is a representation of the percentage of the target element which is visible as a value between 0.0 and 1.0.

     

    ** window.addEventListener('scroll', () =

    scroll은 모든 스크롤 액트에 해당하는 것

    -> 자동으로 스크롤 이동하는 경우에도 observer가 콜백함수를 호출하는 현상이 발생함

     

    ** window.addEventListener('wheel', () =

    -> 반면에 wheel은 사용자가 직접 스크롤을 내리는 경우만 해당한다.

     

    '공부공부' 카테고리의 다른 글

    브라우저  (0) 2022.01.25
    자바스크립트에 대해서 1  (0) 2022.01.23
    IntersectionObserver()  (0) 2022.01.18
    project sorting  (0) 2022.01.18
    project sorting  (0) 2022.01.07
Designed by Tistory.