javascript로 모달구현

코변·2022년 4월 20일
0

개발일지

목록 보기
4/41
    <script>
        const body = document.querySelector('body');
        const modal = document.querySelector('.modal');
        const open_btn = document.querySelector('.open-btn');

        open_btn.addEventListener('click', () => {
            modal.classList.toggle('show');

            if (modal.classList.contains('show')) {
                body.style.overflow = 'hidden';
            }
        });
        modal.addEventListener('click', (event) => {
            if (event.target === modal) {
                modal.classList.toggle('show');


                if (!modal.classList.contains('show')) {
                    body.style.overflow = 'auto';
                }
            }
        });
    </script>

출처: https://7942yongdae.tistory.com/104 [프로그래머 YD]
모달 페이지 구현을 위해 구글링을 하던 중 발견한 코드 클래스 이름 정도만 변경한 이 코드를 jquery 구문으로 그대로 옮겼더니 작동하지 않았다.

    <script>
        const body = $('.body')
        const modal = $('.modal')
        const open_btn = $('.open-btn')

        open_btn.addEventListener('click', () => {
            modal.classList.toggle('show');
            
            if (modal.classList.contains('show')) {
                body.style.overflow = 'hidden';
            }
        })
        modal.addEventListener('click', (event) => {
            if (event.target == modal) {
                modal.classList.toggle('show');

                if (!modal.classList.contains('show')) {
                    body.style.overflow = 'auto';
                }
            }
        })
    </script>

궁금해서 다시 구글링을 해 보았더니 jquery가 반환하는 객체는 jquery객체고 queryselector가 반환하는 객체는 nodelist 즉 native javascript 객체임을 알 수 있었다.

  • 위 코드처럼 jquery를 변수에 담고 사용할 수는 없음
  • 순수 javascript 객체를 조율하고 싶다면 queryselector 나 getElementByID(Or Class)등을 이용하는 것이 좋아보임
  • 내부적 처리면에서도 더 유리하다고 함
profile
내 것인 줄 알았으나 받은 모든 것이 선물이었다.

0개의 댓글