[JS] Scroll 이벤트 리스너

Chen·2024년 6월 14일
0

Javascript

목록 보기
18/22
post-thumbnail

원리

스크롤 중에는 clear로 인해 setTimeout이 실행될 일이 없다가, 스크롤을 멈추면 비로소 0.5초 후에 실행이 되는 원리

기존 prototype 버전

function Character(info) {
    this.mainElm = document.createElement('div');
    this.mainElm.classList.add('character');
    this.mainElm.innerHTML = `<div class="character">
                    쏼라쏼라
                </div>`;
    document.querySelector('.stage').appendChild(this.mainElm);
    this.mainElm.style.left = `${info.xPos}%`;
    // 스크롤 중인지 아닌지 (timeId)
    this.scrollState = null;
    this.init();
}

Character.prototype = {
    constructor: Character,
    init: function () {
        const self = this;

        window.addEventListener('scroll', function () {
            this.clearTimeout(self.scrollState);

            // 스크롤시 timeId라는 숫자를 리턴하니까 => true임
            if (!self.scrollState) {
                self.mainElm.classList.add('running');
                console.log('running 클래스 붙었음');
            }

            self.scrollState = this.setTimeout(function () {
                self.scrollState = null; // 스크롤 멈춤 상태
                self.mainElm.classList.remove('running'); // 시각적으로도 멈추게끔 클래스 remove
            }, 500);
            // console.log(self.scrollState); // return값
        });
    },
};

ES6 class로 변경

class Character {
    constructor(info) {
        this.mainElm = document.createElement('div');
        this.mainElm.classList.add('character');
        this.mainElm.innerHTML = `
            <div class="character">
             쏼라쏼라
            </div>`;
        document.querySelector('.stage').appendChild(this.mainElm);
        this.mainElm.style.left = `${info.xPos}%`;
        this.scrollState = null; // 스크롤 중인지 아닌지 (timeId)
        this.init();
    }

    init() {
        window.addEventListener('scroll', () => {
            clearTimeout(this.scrollState);

            // 스크롤시 timeId라는 숫자를 리턴하니까 => true임
            if (!this.scrollState) {
                this.mainElm.classList.add('running');
                console.log('running 클래스 붙었음');
            }

            this.scrollState = setTimeout(() => {
                this.scrollState = null; // 스크롤 멈춤 상태
                this.mainElm.classList.remove('running'); // 시각적으로도 멈추게끔 클래스 remove
            }, 500);
        });
    }
}

// 예시 Character 객체 생성
const character = new Character({ xPos: 50 });

까다롭고 헷갈리는 init 함수..

profile
현실적인 몽상가

0개의 댓글