본문 바로가기
jQuery

[jQuery] 팝업(popup) / 모달(Modal) 시 스크롤 비활성화 (iOS 포함 모든 기기)

by j. sik 2023. 7. 25.
728x90

팝업(popup)이나 모달(modal) 사용 시 바디의 스크롤(scroll)을 비활성화 하는 방법
iOS(아이폰)를 포함한 모든 기기에 대응

[html]

<body>
  <section class="section1">section1</section>
  <section class="section2">section2</section>
  <div class="popup">popup</div>
  <button class="toggle">popup toggle</button>
</body>

 

[css]

*{ margin: 0; padding: 0; }
body { width: 100%; }
section { height: 600px; }
.section1 { background: yellowgreen; }
.section2 { background: skyblue; }
.popup {
  display: none;
  position: fixed;
  left: 0; top: 0;
  width: 80%; height: 80vh;
  background: violet;
}
.popup.active {
  display: block;
}
.toggle {
  position: fixed;
  left: 10px; top: 30px;
}
.scroll-disable{ /* 스크롤 비활성화 클래스 */
  height:100%;
  min-height:100%;
  overflow:hidden !important;
  touch-action:none;
}

 

[js]

function scrollDisable(){ // body 스크롤 비활성화
  $('body').addClass('scroll-disable').on('scroll touchmove mousewheel', function(e){
      e.preventDefault();
  });
}
function scrollAble(){ // body 스크롤 활성화
  $('body').removeClass('scroll-disable').off('scroll touchmove mousewheel');
}

$('.toggle').click(function(){
  $('.popup').toggleClass('active');
  if($('.popup').hasClass('active')) {
    scrollDisable();
  } else {
    scrollAble();
  }
});

 

See the Pen [jQuery] body scroll lock iOS _ 팝업 메뉴 / 모달 바디 스크롤 비활성화 (모든 기기) by Jinsik Son (@Jinsik-Son) on CodePen.

728x90