[Javascript] 스크롤 위치에 맞춰 팝업을 화면 중앙에 띄우기

2025. 3. 27. 13:00Javascript

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

반응형

팝업을 화면 중앙에 띄우는 방법은 매우 직관적이지만, 스크롤 위치에 따라 팝업의 위치가 달라져야 할 때는 조금 더 신경을 써야 합니다. 이번 포스팅에서는 스크롤 위치에 맞춰 팝업을 화면 중앙에 띄우는 방법을 자바스크립트를 이용해 구현하는 방법을 알아보겠습니다.

 

 

팝업(popup) CSS

팝업을 화면 중앙에 띄우는 기본적인 스타일입니다. transform: translate(-50%, -50%);는 팝업의 크기에 관계없이 정확히 중앙에 배치되도록 해줍니다.

.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  width: 300px;
  height: 200px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 20px;
  display: none; /* 기본적으로 숨김 */
}

 

스크롤에 따라 중앙 위치 조정하기

스크롤을 내리거나 올릴 때 팝업이 화면 중앙에 위치하도록 하려면, 자바스크립트를 사용하여 스크롤 이벤트에 맞춰 팝업의 위치를 동적으로 업데이트해야 합니다.

 

function adjustPopupPosition() {
  const popup = document.querySelector('.popup');
  
  // 뷰포트의 높이에서 팝업의 높이를 빼고, 그 절반을 계산
  const popupHeight = popup.offsetHeight;
  const windowHeight = window.innerHeight;
  
  // 스크롤 위치에 따라 팝업의 top 값을 조정
  const scrollTop = window.scrollY;
  const topPosition = scrollTop + (windowHeight - popupHeight) / 2;
  
  popup.style.top = `${topPosition}px`;
}

// 페이지 로딩 시와 스크롤 시마다 팝업 위치 조정
window.addEventListener('scroll', adjustPopupPosition);
window.addEventListener('resize', adjustPopupPosition);

 

팝업 열기 및 닫기

팝업을 열고 닫는 동작을 구현하기 위해서는 팝업의 display 속성을 조정해야 합니다. 이를 위해 버튼 클릭 시 팝업을 표시하고, 다시 클릭하면 닫히도록 할 수 있습니다.

 

function togglePopup() {
  const popup = document.querySelector('.popup');
  
  if (popup.style.display === 'none' || !popup.style.display) {
    popup.style.display = 'block';
    adjustPopupPosition(); // 팝업이 열릴 때 바로 위치를 맞춤
  } else {
    popup.style.display = 'none';
  }
}

// 버튼 클릭 시 팝업 열기/닫기
document.querySelector('.popup-toggle-btn').addEventListener('click', togglePopup);

 

전체 코드 예시

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>스크롤 위치에 맞춘 팝업</title>
  <style>
    .popup {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: white;
      width: 300px;
      height: 200px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      padding: 20px;
      display: none;
    }
    .popup-toggle-btn {
      position: fixed;
      bottom: 20px;
      right: 20px;
      padding: 10px 20px;
      background-color: #007bff;
      color: white;
      border: none;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <button class="popup-toggle-btn">팝업 열기/닫기</button>
  <div class="popup">
    <h2>팝업 내용</h2>
    <p>여기에 팝업 내용이 들어갑니다.</p>
  </div>

  <script>
    function adjustPopupPosition() {
      const popup = document.querySelector('.popup');
      const popupHeight = popup.offsetHeight;
      const windowHeight = window.innerHeight;
      const scrollTop = window.scrollY;
      const topPosition = scrollTop + (windowHeight - popupHeight) / 2;
      popup.style.top = `${topPosition}px`;
    }

    function togglePopup() {
      const popup = document.querySelector('.popup');
      if (popup.style.display === 'none' || !popup.style.display) {
        popup.style.display = 'block';
        adjustPopupPosition();
      } else {
        popup.style.display = 'none';
      }
    }

    window.addEventListener('scroll', adjustPopupPosition);
    window.addEventListener('resize', adjustPopupPosition);
    document.querySelector('.popup-toggle-btn').addEventListener('click', togglePopup);
  </script>
</body>
</html>

 

 

이 방법을 통해 스크롤 위치에 맞춰 팝업을 화면 중앙에 띄울 수 있습니다. 사용자가 페이지를 스크롤하거나 창 크기를 변경할 때마다 팝업이 중앙에 정확히 위치하게 되어, 보다 직관적인 사용자 경험을 제공할 수 있습니다.

 

 

 

 

[HTML] video vs iframe, 어떤 것이 더 적합할까?

웹 페이지에서 동영상 콘텐츠를 삽입할 때, HTML 태그 중 video와 iframe을 주로 사용합니다. 그러나 이 두 가지 태그는 어떤 차이점이 있을까요? 어떤 것이 더 적합한 선택일까요? 이번에는 video와 ifr

dev-chim.tistory.com

 

 

Array APIs - find(), findIndex(), filter(), map(), some(), every(), reduce(), sort()

find : 배열을 순회하며 요소들 중, 조건에 만족하는 첫 번째 요소만 반환 find(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined; find(predicate: (value: T, index: number, obj: T[]

dev-chim.tistory.com

 

 

[npm] npm 버전 확인, 초기화, 설치 및 옵션, 삭제 등 기본 사용법

npm(node package manage)는 cdn 방식으로 패키지를 가져와서 사용하는 것이 아니라, 모듈화 된 패키지를 node 환경에서 쉽고 간편하게 설치하고 버전 관리할 수 있는 자바스크립트 패키지 매니저입니다.

dev-chim.tistory.com

 

 

[Utility] Microsoft Designer로 쉽게 디자인하기

Microsoft Designer는 간편하고 직관적인 인터페이스를 갖춘 AI(인공지능) 생성 디자인 툴입니다. 사용자가 전문적인 디자인 지식 없이도 손쉽게 다양한 디자인 작업을 할 수 있도록 다양한 템플릿과

dev-chim.tistory.com

 

 

[CSS] 유튜브(Youtube) 영상을 비율 유지한 채 반응형으로 삽입하는 방법

유튜브(Youtube) 영상을 비율 유지한 채 반응형으로 삽입하는 방법에 대해서 알아보겠습니다. iframe 코드 복사하기 데모 영상으로 Google Developers의 영상으로 연습해 보았습니다. 1. 공유 버튼을 클릭

dev-chim.tistory.com

 

 

반응형